【问题标题】:Using ifstream to print integers from text files使用 ifstream 从文本文件中打印整数
【发布时间】:2014-09-21 02:01:58
【问题描述】:

我有一个任务,我应该读取多个包含整数的文件(每行一个),并在对它们进行排序后将它们合并到一个输出文本文件中。我是 C++ 新手,所以我不知道一切是如何工作的。我正在用两个 .txt 文件测试我的程序。第一个文件名为 fileone.txt,包含 1,2,7(我不知道如何格式化,但它们都在不同的行上。)第二个文件名为 filetwo.txt,包含 1,3,5, 9,10(同样每个整数都在不同的行)。

我编写了以下代码,它可以打开两个文件并打印内容。

#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char** argv) {

    ifstream iFile;
    ifstream jFile;
    iFile.open("fileone.txt");
    jFile.open("filetwo.txt");

    int int1 = 0;
    int int2 = 0;
    if (iFile.is_open() && jFile.is_open() ){


        while (iFile.good() || jFile.good() ) {

            iFile >> int1;
            jFile >> int2;

            cout << "From first file:" << int1 << endl;
            cout << "From second file:" << int2 << endl;

        }
    }

    iFile.close();
    jFile.close();

    return 0;
}

这个程序的输出是

我遇到的问题是第一个文件中的最后一个数字被打印了多次。我想要的输出是在打印文件中的最后一个整数后停止打印。仅当第二个文件包含的整数比第一个文件多时,才会出现此问题。有没有办法在第一个文件到达末尾时停止打印,同时仍然打印第二个文件中的所有数字?

【问题讨论】:

    标签: c++ file-io ifstream


    【解决方案1】:

    这样就可以了

       while (iFile || jFile) {
    
            if(iFile >> int1) // make sure the read succeeded!!
                cout << "From first file:" << int1 << endl;
    
            if(jFile >> int2) // make sure the read succeeded!!
                cout << "From second file:" << int2 << endl;
        }
    

    只有在检查数据是否被成功读取后才能真正使用数据。

    【讨论】:

    • 啊,是的。正如我在回答中提到的那样,这是一个更好的成语。
    【解决方案2】:

    考虑改变 while 循环如下

      while (iFile.good() || jFile.good() ) {
        iFile >> int1;
        jFile >> int2;
        int c = iFile.peek();
        int d = jFile.peek();
        if (c == EOF) {
          if (!iFile.eof())
             cout << "From first file:" << int1 << endl;
        } 
       if (d == EOF) {
          if (!jFile.eof())
            cout << "From second file:" << int2 << endl;
            }
       }
    

    问题是检查文件的结尾并处理是否打印它。您可以使用上述 eof() 函数。

    我还没有检查代码。但逻辑应该是正确的。

    【讨论】:

    • 不必要的复杂
    • @Nabin 没有真正必要的改进。还是太复杂了!
    猜你喜欢
    • 2011-12-28
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2015-06-04
    相关资源
    最近更新 更多