I have 2 questions:
What happens to s if I again do a \"getline(in,line)\" after the while loop ends?
ifstream in(\"string.txt\");
string s, lin
What happens to s if I again do a "getline(in,line)" after the while loop ends?
The loop ends when std::getline()
returns something that resembles a boolean false
. When you look at the signature of the function you will see that it returns the stream. Streams have an implicit conversion to something boolean-like that resembles their state. If if(stream)
evaluates the stream to false
, then that means that the stream is in a bad state. This could be the EOF flag set or one of the error flags, or both.
Any attempt to use a stream that is in a bad state will fail. Nothing will be read.
The getline() function: everytime it is called, does it goes to the "next" line of the ifstream "in" object in the above code? If so what happens when the while loop ends and I call the same function again? (almost the same as first question, just a subtle difference)
This has nothing to do with std::getline()
. The position in the opened file is a property of the (file) stream. Every time you (re-)open the file for reading (without passing extra parameter for setting the position), the position is set to the beginning of the stream (file).
getline
reads the stream until it encounters the newline character or reaches the end of stream. In latter case, the steam will have its failbit set. This translates to breaking the while
loop in your example, because getline
returns the (reference to) stream which is get cast to bool
, yielding stream's state that is false
because of aforementioned failbit.
In such conditions, subsequent calls to getline
will do nothing as the stream is still in the 'fail' state. You could clear it with istream::clear
, but since there is no more data in it, it have its failbit set again on next read.