如何使用 C++ 获取文本文件中的整数总和?
How can I get the sum of integers in a text file with c++?
如果这是一个简单的问题,我深表歉意,我正在自学 C++,似乎无法在任何地方找到我正在寻找的解决方案。
假设我有一个文本文件,其中的数据组织如下:
10 - 示例 1
20 - 样本 2
30 - 示例 3
40 - 样本 4
有没有办法从每一行中获取数字并将它们的总和存储在一个变量中?还是我不正确地处理这个问题?
提前致谢!
您需要在头文件列表中包含 <fstream>
。
然后:
1- 打开您的文件。
2- 逐行阅读。
3- 总结数字。
4- 打印总数。
您需要阅读有关文件的内容才能完全理解其工作原理
int main()
{
fstream MyFile; // declare a file
MyFile.open("c:\temp\Numbers.txt", ios::in); // open the file
int sum = 0;
string line;
while (getline(MyFile, line)) //reading a line from the file while possible
{
sum = sum + stoi(line); // convert string to number and add it to the sum
}
MyFile.close(); // closing the file
cout << "sum is: " << sum; // print the sum
cin.get();
return 0;
}
如果这是一个简单的问题,我深表歉意,我正在自学 C++,似乎无法在任何地方找到我正在寻找的解决方案。
假设我有一个文本文件,其中的数据组织如下:
10 - 示例 1
20 - 样本 2
30 - 示例 3
40 - 样本 4
有没有办法从每一行中获取数字并将它们的总和存储在一个变量中?还是我不正确地处理这个问题? 提前致谢!
您需要在头文件列表中包含 <fstream>
。
然后:
1- 打开您的文件。
2- 逐行阅读。
3- 总结数字。
4- 打印总数。
您需要阅读有关文件的内容才能完全理解其工作原理
int main()
{
fstream MyFile; // declare a file
MyFile.open("c:\temp\Numbers.txt", ios::in); // open the file
int sum = 0;
string line;
while (getline(MyFile, line)) //reading a line from the file while possible
{
sum = sum + stoi(line); // convert string to number and add it to the sum
}
MyFile.close(); // closing the file
cout << "sum is: " << sum; // print the sum
cin.get();
return 0;
}