Question about end of file file

I am reading several files. There are about 300 of them. For some reason, if I set a loop to perform three iterations, the while loop, which should go through each line, becomes infinite. My question is: is there something that I forget to include in my cycle? At the moment, I'm just trying to read one line at a time, eventually storing some data in the output file. Or is it possible that there is something in the data files that prevents the program from reaching the end of the file?

ifstream inFile; ofstream outFile; char outputFilename[] = "output.txt"; int i; outFile.open(outputFilename, ios::out); for (i = 1; i < 4; i++) { stringstream inputFilename; inputFilename << "data/" << i << ".txt"; inFile.open(inputFilename.str().c_str(), ios::in); if (!inFile) { cout << "Error opening input files" << endl; exit(-1); } char buffer[256]; while (!inFile.eof()) { cout << "HEY"; inFile.getline(buffer, 100); } inFile.close(); } outFile.close(); 

Update: it works much better.

 char buffer[256]; while (!inFile.eof()) { inFile >> buffer; } 
+4
source share
2 answers

It makes no sense to check the end of the file before reading. Try this circuit instead:

  char buffer[256]; while (inFile.getline(buffer, 100)) { cout << "HEY"; } 

or better yet

  std::string buffer; while (std::getline(inFile, buffer)) { cout << "HEY"; } 

EDIT: fix stoopid error in string version.

+3
source

Again!

Among other things:

 while (!inFile.eof()) { cout << "HEY"; inFile.getline(buffer, 100); 

it should be:

 while ( inFile.getline(buffer, 100) ) { cout << "HEY"; 

as a moment, think or report your docs to eof ().

+2
source

All Articles