gpt4 book ai didi

c++ - FStream - 读取文件 C++ 中的整数

转载 作者:行者123 更新时间:2023-11-28 02:17:50 25 4
gpt4 key购买 nike

目标是读取以下文件中的每个整数并将它们全部相加。但由于某种原因,我似乎无法将字符串行转换为 int。代码:

#include <iostream>
#include <fstream>
using namespace std;

int main(){

string line;
ifstream file ("Random.txt");
int lines;
int amount = 0;
while(getline(file, line)){
lines++;
amount += static_cast<int>(line);
}

cout << amount;
return 0;

}

文本文件:

2
3
4
6

任何帮助将不胜感激

最佳答案

不,你不能将这样的字符串转换为任何东西,真的。

如果你知道文件只包含整数,你可以直接读取它们:

int   number;
while (file >> number)
{
++lines;
amount += number;
}

关于c++ - FStream - 读取文件 C++ 中的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33509866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com