Simple program opens a text file and counts all the lines. Then it returns the pointer to the beginning of the file and starts pulling in the lines for data manipulation.
The Problem: If the file "triangle.txt" ends with a newline everything works fine until the last while loop which becomes an infinite loop. When the newline is removed the output is fine. Why does a newline at the end of a text file break getline the second time through a file?
#include <iostream>
#include <fstream>
#include <string> //strings strtok strtol
using namespace std;
int main()
{
ifstream ftext;
ftext.open("triangle.txt",fstream::in);
if (!ftext.is_open()){
cout<< "Error opening file.";
return 0;
}
int size = 0;
string row;
while (!ftext.eof()){
getline(ftext,row);
size++; //size will equal the number of rows
}
cout<< "This pyramid is " << size<< " stories tall.\n";
//problem starts here...
ftext.seekg(0, ifstream::beg); //move back to beginning
ftext.clear(); //reset flags
while (!ftext.eof()){
getline(ftext,row);//with \n at eof this pulls in nothing
cout<<row.data()<<"\n"
}
}