Open the file with std::ifstream in("file.txt"), check if (!in), then loop with while (std::getline(in, line)): each pass puts one line, without its newline, in a std::string, and the loop ends at the end of the file. Never loop on while (!in.eof()). To read the whole file into one string, use std::ostringstream ss; ss << in.rdbuf();.
Reading a text file in C++ takes three pieces from <fstream> and <string>: an std::ifstream that opens the file, std::getline that reads up to the next newline, and the stream's own true/false state that tells you when a read failed. Most bugs in this area come from testing that state at the wrong moment. The sections below cover the standard loop, parsing values out of each line, the classic traps (eof() loops, >> followed by getline, Windows line endings), reading a whole file into a string, and finding out why a file did not open. Each example writes its own input file first and runs on this page: hit Run, then edit the code and run it again.
1std::ifstream and a std::getline loopRecommended
std::getline(in, line) reads characters up to the next '\n', stores them in line without the newline, and returns the stream. A stream converts to false once a read has failed, so putting the call in the while condition reads every line and stops right after the last one. Check the stream once after opening it: an ifstream that could not open the file does not throw, it just fails every read.
#include <fstream> #include <iostream> #include <string> #include <vector> int main() { // Write a small file to read; the last line has no newline at the end { std::ofstream out("notes.txt"); out << "first line\n" "\n" " spaces kept \n" "last line, no newline"; } // out is closed here, so the text is on disk std::ifstream in("notes.txt"); if (!in) { std::cout << "could not open notes.txt\n"; return 1; } // getline returns the stream, which tests false once a read fails std::string line; int number = 0; while (std::getline(in, line)) { ++number; std::cout << number << ": [" << line << "] " << line.size() << " chars\n"; } // Read it again into a vector. The loop above ended with failbit set, // so clear() it first, or seekg and every read after it fail too in.clear(); in.seekg(0); std::vector<std::string> lines; while (std::getline(in, line)) { lines.push_back(line); } std::cout << lines.size() << " lines, last: " << lines.back() << '\n'; }
Output
Every line comes back as it is in the file, minus the newline: the blank line is 2: [] 0 chars, the spaces survive in 3: [ spaces kept ] 15 chars, and a last line with no newline at the end is still read, as 4: [last line, no newline] 21 chars. The second pass collects them into a vector and prints 4 lines, last: last line, no newline. It needs in.clear() first: the first loop ended because a read failed, which set failbit, and while that flag is set seekg and every read do nothing. Opening a second std::ifstream works too. The file closes itself when in goes out of scope, so there is no close() to forget. To split each line on a delimiter, see splitting a string.
2Parsing values from each line
The most-voted version of the question has a file of number pairs such as 5 3 on each line. You can read them with >> straight from the file, or read a line with getline and then parse it from a std::istringstream. The second way is longer but knows where each line starts and ends, so it can reject one bad line and carry on with the next.
#include <fstream> #include <iostream> #include <sstream> #include <string> int main() { { std::ofstream out("pairs.txt"); out << "5 3\n6 4\n7 x\n9 1 2\n8 2\n"; } // Line by line: each line is parsed on its own, so a bad one // can be reported and skipped without losing the rest std::ifstream in("pairs.txt"); std::string line; int line_no = 0; while (std::getline(in, line)) { ++line_no; std::istringstream fields(line); int a, b; if (!(fields >> a >> b)) { std::cout << "line " << line_no << ": not two numbers [" << line << "]\n"; continue; } // Skip trailing whitespace; anything left over is extra text fields >> std::ws; if (!fields.eof()) { std::cout << "line " << line_no << ": extra text [" << line << "]\n"; continue; } std::cout << a << " + " << b << " = " << a + b << '\n'; } // Value by value: shorter, but it ignores line breaks // and stops for good at the first token that is not a number std::ifstream in2("pairs.txt"); int a, b; int pairs = 0; while (in2 >> a >> b) { ++pairs; } std::cout << "operator>> read " << pairs << " pairs, then stopped\n"; }
Output
Line by line, the good lines print 5 + 3 = 8, 6 + 4 = 10 and 8 + 2 = 10, and the two bad ones are named: line 3: not two numbers [7 x] and line 4: extra text [9 1 2]. The std::ws check is what catches the third number; without it, 9 1 would pass and the 2 would be ignored. Reading with >> alone prints operator>> read 2 pairs, then stopped: the x put the stream in a failed state and nothing after it was read, with no error message. while (in >> a >> b) is fine for files you produced yourself; for anything a person typed, parse line by line. To turn a field into a number with full error checking, see converting a string to an int.
3Traps: eof() loops, >> before getline, \r\n
Three mistakes account for most "my loop reads one line too many" and "getline returns an empty string" questions. while (!in.eof()) asks whether a read has already hit the end, not whether the next one will. in >> count stops in front of the line break, so a getline right after it reads only what is left of that line. And a file saved on Windows ends each line with \r\n; on Linux and macOS getline removes only the \n.
#include <fstream> #include <iostream> #include <string> int main() { { std::ofstream out("items.txt"); out << "apple\nbanana\n"; } // Wrong: eof() turns true only AFTER a read has failed, // so the body runs once more with nothing read std::ifstream in("items.txt"); std::string line; while (!in.eof()) { std::getline(in, line); std::cout << "eof loop: [" << line << "]\n"; } // Right: test the read itself std::ifstream in2("items.txt"); while (std::getline(in2, line)) { std::cout << "getline loop: [" << line << "]\n"; } // A count line, then names, saved with Windows line endings { std::ofstream out("names.txt"); out << "2\r\nAda Lovelace\r\nAlan Turing\r\n"; } // Trap: >> stops before the line break, so the next getline // reads the rest of the count line, which is just "\r" std::ifstream in3("names.txt"); int count = 0; in3 >> count; std::getline(in3, line); std::cout << "after >>: " << line.size() << " char(s) left on the line\n"; // Fix: std::ws skips the leftover whitespace, and pop_back() // removes the '\r' that getline keeps from a "\r\n" ending std::ifstream in4("names.txt"); in4 >> count >> std::ws; for (int i = 0; i < count && std::getline(in4, line); ++i) { if (!line.empty() && line.back() == '\r') { line.pop_back(); } std::cout << "name: [" << line << "] " << line.size() << " chars\n"; } }
Output
The eof() loop prints a third, empty line, eof loop: []: after banana the stream has not yet tried to read past the end, so the body runs once more, that getline fails, and the code uses the empty result anyway. The getline loop prints exactly the two lines. After in3 >> count the next getline gets the rest of the count line: after >>: 1 char(s) left on the line, the \r (with a plain \n ending it would be an empty string). Reading >> std::ws skips that whitespace, and stripping a final \r gives name: [Ada Lovelace] 12 chars and name: [Alan Turing] 11 chars. On Windows, a file opened in text mode already turns \r\n into \n, but the check costs nothing and makes the code portable.
4Read a whole file into a std::string
When you want the file in one string (to search it, hash it or hand it to a parser), skip the line loop. ss << in.rdbuf() copies the file's whole buffer into a std::ostringstream. std::istreambuf_iterator does it in one declaration. For big files, asking std::filesystem::file_size first and doing one read into a string of that size avoids growing the string as it fills. Open the file in std::ios::binary so the bytes come back unchanged on every platform.
#include <filesystem> #include <fstream> #include <iostream> #include <iterator> #include <sstream> #include <stdexcept> #include <string> // Read a whole file into a string through a stringstream std::string read_all(const std::string& path) { std::ifstream in(path, std::ios::binary); // binary: bytes as they are if (!in) { throw std::runtime_error("cannot open " + path); } std::ostringstream ss; ss << in.rdbuf(); return ss.str(); } int main() { { std::ofstream out("config.ini"); out << "[server]\nport=8080\nhost=localhost\n"; } std::string text = read_all("config.ini"); std::cout << text.size() << " bytes:\n" << text; // istreambuf_iterator: one statement, and {} is the end iterator std::ifstream in("config.ini", std::ios::binary); std::string text2(std::istreambuf_iterator<char>(in), {}); std::cout << "same text: " << std::boolalpha << (text2 == text) << '\n'; // Ask for the size, then fill a string of that size in one read auto size = std::filesystem::file_size("config.ini"); std::string text3(size, '\0'); std::ifstream in3("config.ini", std::ios::binary); in3.read(text3.data(), static_cast<std::streamsize>(size)); std::cout << "read " << in3.gcount() << " of " << size << " bytes\n"; try { read_all("missing.ini"); } catch (const std::exception& e) { std::cout << "error: " << e.what() << '\n'; } }
Output
read_all returns all 34 bytes, newlines included, and the other two ways read the same thing: same text: true and read 34 of 34 bytes. The {} in the iterator version matters: the older spelling std::string s(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()); declares a function named s instead of a string (the "most vexing parse"). read_all checks the stream before reading because ss << in.rdbuf() on a file that did not open gives back an empty string with no error; here it throws instead and prints error: cannot open missing.ini. To work through the text afterwards, split it into lines with a std::istringstream and the same getline loop.
5When the file will not open
A failed open shows up only as a false stream, so print a reason yourself. Two things help: the working directory, because a relative path such as "data.txt" is looked up from wherever the program was started, and std::strerror(errno), which turns the operating system's error code into text. Turning on stream exceptions looks like a cleaner alternative, but failbit is also how a normal getline loop ends.
#include <cerrno> #include <cstring> #include <filesystem> #include <fstream> #include <iostream> #include <string> int main() { // A relative path is looked up from the working directory, // not from the folder that holds the source file or the binary std::cout << "cwd: " << std::filesystem::current_path().string() << '\n'; std::ifstream in("missing.txt"); if (!in) { // The standard does not promise errno here, but GCC on Linux // sets it from the failed open() call underneath std::cout << "cannot open missing.txt: " << std::strerror(errno) << '\n'; } std::cout << "is_open: " << std::boolalpha << in.is_open() << '\n'; { std::ofstream out("two.txt"); out << "one\ntwo\n"; } // Exceptions on failbit also fire at the normal end of a getline loop std::ifstream f("two.txt"); f.exceptions(std::ifstream::failbit | std::ifstream::badbit); std::string line; try { while (std::getline(f, line)) { std::cout << "read: " << line << '\n'; } } catch (const std::ios_base::failure& e) { std::cout << "threw at end of file: " << e.what() << '\n'; } }
Output
This page runs programs in cwd: /tmp/workspace, so that is where missing.txt was looked for, and the reason prints as cannot open missing.txt: No such file or directory, with is_open: false. In an IDE the working directory is often the build folder, which is why a file next to the source "cannot be found". With failbit exceptions on, the loop reads one and two, then the end of the file itself throws: threw at end of file: basic_ios::clear: iostream error. If you want exceptions, enable only std::ifstream::badbit (a real read error) and keep the if (!in) check after opening.
6Which should you use?
| Method | Reads | Watch out for | Best for |
|---|---|---|---|
| while (std::getline(in, line)) | One line at a time | A \r left by Windows files | Almost every text file |
| getline + std::istringstream | Values from each line | Check for extra text with std::ws | Records, input people typed |
| while (in >> a >> b) | Values, ignoring lines | Stops silently at a bad token | Clean files of numbers or words |
| ss << in.rdbuf() | Whole file | Check the open first | File into one std::string |
| istreambuf_iterator | Whole file | The most vexing parse | A one-statement read |
| file_size + in.read | Whole file | Open in binary mode | Large files, one allocation |
| while (!in.eof()) | One extra pass | Uses a failed read | Avoid |
Frequently asked questions
Why does my C++ file loop read the last line twice?
Because the loop tests in.eof() (or in.good()) before reading. Those flags only change after a read has failed, so the body runs once more after the last line, the read fails, and the code uses whatever is left in the variable: an empty string with getline, or a stale or zero value with >>. Put the read in the condition instead: while (std::getline(in, line)) or while (in >> x).
How do I read a file into a vector of lines in C++?
Loop with std::getline and push each line: std::vector<std::string> lines; std::string line; while (std::getline(in, line)) lines.push_back(line);. Empty lines become empty strings, and a last line with no trailing newline is still read. Strip a trailing \r if the file may come from Windows.
Why does getline return an empty string after >>?
in >> n reads the number and stops in front of the newline that follows it, so the next std::getline reads from there to that newline: an empty string, or "\r" in a Windows file. Skip the leftover whitespace first with in >> n >> std::ws;, or call in.ignore(std::numeric_limits<std::streamsize>::max(), '\n') to drop the rest of the line. The same applies to std::cin >> n followed by std::getline(std::cin, s).
What is the fastest way to read a whole file in C++?
Get the size with std::filesystem::file_size, create a std::string of that size and fill it with one in.read(s.data(), size) on a stream opened with std::ios::binary. ss << in.rdbuf() is nearly as fast for most files and shorter to write. Character-by-character reads with in.get() or istreambuf_iterator are usually slower, though fine for small files.
Why can't my C++ program find the file I want to read?
A relative path such as "data.txt" is resolved against the working directory the program was started in, not the folder with the source file or the executable. IDEs often start programs in a build folder. Print std::filesystem::current_path() to see where it is looking, and std::strerror(errno) after a failed open for the reason, such as No such file or directory. Or pass an absolute path.
How do I read a file word by word in C++?
Use >> with a std::string: std::string word; while (in >> word) { ... }. Each read skips any spaces, tabs and newlines and returns the next run of non-whitespace characters, so line breaks do not matter. Read into an int or double the same way for a file of numbers; the loop stops at the end of the file or at the first token that is not a number.