reading from a .txt file

The code is supposed to tell the number of lines in a .txt file and show it contents line by line

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line;
ifstream infile;
infile.open("sample.text");
string s;
int count = 0;
while ((getline(infile, line)))
count++;
cout << count << endl;
if (infile.fail())
cout << "not working" << endl;
else
while(getline(infile, s))
cout << s << endl;
}
The program displays the error message after counting the lines
How can I get it to continue?
Last edited on
Please use code tags in your posts. Highlight the code and click the <> button to the right of the edit window.

Change if (infile.fail()) to if (!infile.eof())
Also, to print out the file, you'll have to seek back to the beginning:
infile.seekg(0, ios_base::beg);

Be careful when placing that code! You will probably find that you need to add { and } somewhere to get the block structure of the code right.
I am so sorry for not using the code tags

Thank you very much, your recommendations worked!
Topic archived. No new replies allowed.