Using ifstream to print integers from text files

隐身守侯 提交于 2019-12-24 02:23:25

问题


I have an assignment where I am supposed to read multiple files containing integers (one on each line) and merge them into a output text file after sorting them. I am new to C++ so I do not know how everything works. I am testing my program with two .txt files. The first file is called fileone.txt, contains 1,2,7 (I do not know how to format this but they are all on different lines.) The second file is called filetwo.txt, and contains 1,3,5,9,10 (again every integer is on a different line).

I have written the following code which opens both files and prints the contents.

#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;
}

The output of this program is

The problem I am having is the last number in the first file gets printed multiple times. The output I want is to stop printing after printing the last integer from the file. The problem only appears when the second file contains more integers than the first one. Is there a way to stop printing from the first file when it reaches the end and while still print all the numbers from the second file?


回答1:


This will do the trick

   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;
    }

You should only really use data if you checked to see if it was successfully read.




回答2:


Consider changing the while loop as follow

  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;
        }
   }

The thing is to check the end of file and handle if to print it. You can use eof() function as above.

I haven't checked the code. But the logic should be correct.



来源:https://stackoverflow.com/questions/25955075/using-ifstream-to-print-integers-from-text-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!