首先,我将其标记为家庭作业问题 我已经坚持了一个星期,因为我似乎无法弄清楚我做错了什么而且我正在希望 SO 的好人能再次来救我(过去一周我搜索了 SO 和其他 C++ 站点,但提供的解决方案并没有解决问题——但是我可能错误地设置了循环.
作业:给定一个文本文件 numbers.txt(其中包含 9,999 个数字,范围从 1 到 10,000,随机排序,连续列表中缺少一个数字)作业是使用 void 函数来确定丢失的整数是什么。
我尝试了什么:我最后一次尝试包含以下代码:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
void find_number();
int main()
{
...
find_number();
}
void find_number();
{
int sum = 0;
int sum1 = 0;
int num;
for (int i = 1; i <= 10000; i++)
sum += i;
cout << "The sum of all the numbers between 1 and 10,000 is: " << sum << endl;
ifstream numbers;
numbers.open("numbers.txt");
if (!numbers.good()) {
return;
cout << "Error! Unable to open file!";
}
if (numbers) {
numbers >> num;
sum1 += num;
}
numbers.close();
cout << "The sum of all the numbers contained in the text file \"numbers.txt\" is: " << sum1 << endl;
cout << "By subtracting the sum of the text file from the sum of 1 to 10,000 the consecutive number missing from the text file is: " << sum - sum1 << endl;
}
我做错了什么?感谢您的帮助。
最佳答案
至少有两个错误:
返回语句在诊断输出之前执行
if (!numbers.good()) { return; cout << "Error! Unable to open file!"; }
以下行将执行一次而不是读取整个文件:
if (numbers) { numbers >> num; sum1 += num; }
您可以根据以下建议改进您的代码:
提取号码的同时查看流状态:
while(numbers >> num) sum1 += num;
您不需要关闭文件流,它会在其析构函数中自动完成。
您可以在文件流初始化时打开文件:
ifstream numbers("numbers.txt");
关于c++ - 使用 C++ 循环从加载的 TXT 文件执行计算时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26998726/