c++ - 函数不能正确计算文件中的整数?
问题描述
我正在制作一个非常简单的函数,我制作了一个整数数组,我在一个文件中写入,然后我从同一个文件中读取并返回放在文件中的值的数量。从技术上讲,该值应该与数组的长度相同,但是结果是不同的。我在循环中放了一些 couts,但不明白问题可能出在哪里。
int len = 5;
int main()
{
int A[len];
for (int i = 0; i < len; i = i + 1) {
cout << "insert a value: " << endl;
cin >> A[i];
}
ofstream file;
file.open("trial.txt");
for (int i = 0; i < len; i = i + 1) {
file << A[i] << '\t';
}
file.close();
ifstream file1;
file1.open("trial.txt");
int val;
int conta = 0;
cout << "count before while" << conta << endl;
while (!file1.eof()) {
file1 >> val;
cout << "i am val: " << val << endl;
cout << "i am conta:" << conta << endl;
conta = conta + 1;
}
cout << "i am conta after while: " << conta << endl;
cout << "the value should be 5: " << conta; //instead it shows 6
file1.close();
}
解决方案
这是标准问题!不要使用这种循环:while (!file1.eof())
它不起作用,因为您的文件以选项卡结尾,该选项卡不是以最后一个数字读取的,因此循环再次迭代比需要的次数更多。在最后一次迭代中读取选项卡,但读取val
失败,您将其视为重复值。
像这样修复它:
while (file1 >> val) {
cout << "i am val: " << val << endl;
cout << "i am conta:" << conta << endl;
conta = conta + 1;
}
它尝试读取整数值,并且只有在成功时才会执行循环。导致此循环停止的原因可能有多种:到达文件末尾、未找到整数值、IO 操作失败。
题外话:这int A[len];
在标准中是不允许的C++
。它适用于大多数编译器,因为它允许在C
. 在 C++ 中,建议使用std::array
(since C++11
) 或std::vector
在这种情况下。
推荐阅读
- javascript - 如何在 ES6 中创建 for...of 实例?
- c++ - Cocos2d-x v4.0 在带有 Xcode 12、Xcode 12.1、Xcode 12.2 的 iPhone 模拟器中崩溃
- mysql - 如何在 VB.Net 中分别检查是否有 2 个或更多查询正在执行
- ios - 我在 ios webview 应用程序中使用 iframe 加载网站,但窗口已打开
- css - 删除手机的完美滚动条
- java - 使用 Java 从服务器主机存储和检索数据
- assembly - 为什么在摩托罗拉 68k 中,对于非常大的循环计数,dbra 如此之快?
- javascript - 如何删除数组中的重复元素?
- reactjs - 如何将 React Hook 用于 componentWillReceiveProps
- ios - 即使在出于软件包目的卸载应用程序之后,也可以唯一地识别 iOS 设备