0

I am currently trying to read input from a text file with only one line in C++; I am able to extract the one line of text from the file successfully to a string using the std::getline(file, string). After extracting the line there is no more text. When I try to check the state of the stream, it will never return false when file.good() is called, and the known "end" of the file is reached. Why is this? See code below:

#include<fstream>
#include<cstring>
using namespace std;

  ifstream file;
  string test;
  file.open("HW6.txt");//HW6.text is one line text file
  getline(file,test);//extracts the line of text; file should be blank now
  cout<<file.good(); //this returns true
  getline(file,test); //attempt to extract text from blank file
  cout<<file.good(); //this returns true still

2 Answers 2

1

There is very nice summary, in tabular form, of when istream::good() returns true and false at http://en.cppreference.com/w/cpp/io/basic_ios/good.

istream::good() returns true only when none of the the following flags is true:

eofbit
failbit
badbit 

In your case, the stream is still in good condition since you didn't try to read anything else after successfully reading the line.

Sign up to request clarification or add additional context in comments.

4 Comments

Additional calls to getline and calls to good( ) after the initial call still return true. I'm sorry I forgot to mention that in the original post.
In your update, you said "blank line". That is still a valid line as far as std::getline() is concerned.
So if I were construct a while loop to extract multiple lines, what conditional statement will terminate reading once all of the lines from a file have been read. Essentially, the end of file has been reached? I want to loop while there is text. Once there is no more text, I want the loop to be done.
You can terminate a while loop using an infinite number of conditions. Terminate when the first character is q. Terminate when the line has only white space. Terminate when the line contains no numbers. And so on
0

Here's an example taken from cplusplus.com.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, char **argv)
{
  string line;
  ifstream f(argv[1]);
  if (f.is_open()) {
    while ( getline (f,line) ) {
      // if (line.size())
      cout << line << endl;
    }
    f.close();
  } else cerr << "Unable to open file " << argv[1] << endl;

  return 0;
}

You can uncomment the if statement, if you don't need blank lines.

2 Comments

the while (getline, f,line) in my cases loops endlessly. Any idea why this could be?
Must be a typo in your code. getline returns false once it tries to read past the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.