首页 > 解决方案 > 函数不能正确计算文件中的整数?

问题描述

我正在制作一个非常简单的函数,我制作了一个整数数组,我在一个文件中写入,然后我从同一个文件中读取并返回放在文件中的值的数量。从技术上讲,该值应该与数组的长度相同,但是结果是不同的。我在循环中放了一些 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();
}

标签: c++ifstreamofstream

解决方案


这是标准问题!不要使用这种循环: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在这种情况下。


推荐阅读