Hi, how does getline reads the 2nd line if getline function is called again since it doesn't have a '\n' to skip to the next line.
2nd question does the program move to read the next character automatically in C++ after reading the current character? sorry, if my question is not clear. I am not sure this works.
1st qns
1 2 3 4 5 6 7 8 9
while(!in_file.eof())
{
getline(in_file, line);
cout << line << endl;
}
Looping on a stream being eof is not a good idea. When std::getline reads the entire file line by line and there is no more data in the file the file is not flagged as being at end-of-file. The attempt to read the file past EOF will then flag the file. Loop on a successful file read:
When std::getline tries to extract a line past the last line in the file the extraction fails and the while loop terminates.
How does std::getline "know" how to read a line of data? It extracts data from the file until either all data is extracted or it extracts a newline ('\n') character. The newline is not added to the std::string, though it is extracted from the file's input stream. The stream's input stream pointer is then positioned to the next potential character in the file. https://cplusplus.com/reference/string/basic_string/getline/
There is an overload for the programmer to use a different character deliminator other than a newline.
> how does getline reads the 2nd line if getline function is called again
> since it doesn't have a '\n' to skip to the next line.
std::getline reads the current line, it extracts the delimiter and throws it away.
When std::getline is called again, the the current line is the next line.
> does the program move to read the next character automatically in C++ after reading the current character?
Yes. It reads the next character and extracts it (removes it from the input buffer).