使用循环从加载的 TXT 文件执行计算时出现问题C++
Trouble performing calculations from loaded TXT file using C++ loop
首先,我会将此标记为家庭作业问题,我已经坚持了一个星期,因为我似乎无法弄清楚我做错了什么,我希望 SO 的优秀人员可以再次拯救我(过去一周我已经搜索了 SO 和其他C++网站,但提供的解决方案并没有纠正这个问题 - 但是我可能设置了错误的循环。
赋值:给定一个文本文件编号.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;
}
我做错了什么?感谢您的任何帮助。
至少有两个错误:
-
return 语句在诊断输出之前执行
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");
提示:您没有读取整个文件
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 递归函数计算序列中的平方和(并输出过程)
- (C++)分析树以计算返回错误值的简单算术表达式
- 我的字符计数代码计算错误.为什么
- 在计算中使用二的幂有多有利可图
- 如何计算文件中的"columns"数?
- 计算排序向量的向量中唯一值的计数
- 如何使用 std::累积在 C++ 中计算总和立方体
- 使用Qt C++计算类似Git的SHA1哈希
- OpenCV C++.快速计算混淆矩阵
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- C++如何计算用户输入的数字中的偶数位数
- 如何计算数据类型的范围,例如int
- 类似枚举的计算常量
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 计算缩放多边形的比例,得到给定的多边形面积
- 在C++中如何在没有pow的情况下进行基础计算
- 计算平均值,不包括上次得分
- 如何计算多映射中重复对的数量