File I/O -> getline() Returns Empty

I've been pulling my hair out trying to figure this out. I've done file I/O before and nothing like this has happened to me before. I have a text file from which I am just trying to read the first line. However, when I call getline(), I get nothing. I'm sure I'm just doing something stupid. Also, I've tried using ignore() and sync() from other solutions to no avail. Thanks!

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

void getState();

std::ifstream gState("state.txt", std::ios_base::app); // Read from state file

int main() {

	getState();

	return 0;
}

void getState() {

	std::string state = "";
        
        getline(gState, state);

	std::cout << state << std::endl;

}


The output is empty. Again, the text file already has data.
Firstly, you use an ifstream, therefore you do not need std::ios_base::app, which is for output operations.

Your code works just fine for me. The problem is most likely with the text file. It could be that you are compiling on Linux using a text file created on Windows, which means that the newline characters are encoded differently (CRLF vs LF).

Or you could possibly have a newline as the very first line in the file, in which case, nothing is printed out.
Last edited on
Got it!

I removed std::ios_base::app, and everything is working!

Thanks!
Topic archived. No new replies allowed.