Using ifstream to print integers from text files

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 <img src="https://i.stack.imgur.com/L6gjJ.png" alt="enter image description here">

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?

Answer1:

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.

Answer2:

Consider changing the <strong>while</strong> 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 <strong>eof()</strong> function as above.

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

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:Using ifstream to print integers from text files