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).