how does the program get to the next line or next char? ?

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;

}


2nd qns
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <fstream>

using namespace std;

int main()
{
    ifstream readFile("hey.txt" );

    ofstream writeFile("hi.txt", ios::app);

    char x;

    while(readFile >> x)
    {
        writeFile << x << "***";

    }

      writeFile << endl;

}
Last edited on
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <fstream>
#include <string>

int main()
{
	std::ifstream ifile ("some_test.txt");

	std::string str;

	while (std::getline(ifile, str))
	{
		std::cout << str << '\n';
	}
}

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.

The second code snippet extracts a single character repeatedly. When operator>> tries to extract past the end of the file the extraction fails and the while loop terminates.
https://cplusplus.com/reference/istream/istream/operator-free/
> 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).

To read the next character without extracting it, use peek()
https://en.cppreference.com/w/cpp/io/basic_istream/peek
Topic archived. No new replies allowed.