Read from File in C++
Read a text file in C++ with ifstream: getline to read line by line, >> to read word by word, and why while(!eof()) prints the last line twice.
1#include <iostream>2#include <fstream>3#include <string>4using namespace std;56int main() {7 // Open file for reading8 ifstream inFile("data.txt");910 if (inFile.is_open()) {11 string line;1213 cout << "Reading file line by line:" << endl;14 while (getline(inFile, line)) {15 cout << line << endl;16 }1718 inFile.close();19 } else {20 cout << "Error: Unable to open file for reading." << endl;21 }2223 // Alternative: Read word by word24 ifstream inFile2("data.txt");25 if (inFile2.is_open()) {26 string word;27 cout << "\nReading file word by word:" << endl;28 while (inFile2 >> word) {29 cout << word << " ";30 }31 cout << endl;32 inFile2.close();33 }3435 return 0;36}
Sample Output
100 200 300
Read as a text line, not as numbers.
Hello, World! This is a C++ ...
>> splits on whitespace and keeps punctuation.
In this one
- How to read a file line by line with getline
- How >> reads word by word and skips newlines
- Why the stream itself is the loop condition
- Why while(!eof()) is a bug
How it works
- 1
Open data.txt with ifstream and check is_open().
- 2
getline in a loop and print each line.
- 3
Close the stream.
- 4
Open a second stream and read with >> word.
- 5
Print every word separated by spaces.
Edge cases
File missing
Delete data.txt and run.
is_open() is false, so the error message prints. The second block is skipped because inFile2 also fails to open.
Last line has no newline
Save a file whose last line has no trailing newline.
getline still returns that line; the loop then ends on the next call.
Empty lines
Add a blank line to the file.
getline returns an empty string for it, so a blank line prints. The >> loop skips it entirely.
What's going on
This program reads data.txt (written by the file-write program) twice: once line by line, and once word by word. Run file-write first, or the error branch prints.
ifstream inFile("data.txt"); opens the file for reading. is_open() is false if the file is missing or cannot be read.
while (getline(inFile, line)) is the standard way to read a text file. Each call reads up to the next newline, stores the text in line without the newline, and returns the stream. A stream converts to true while reads succeed, so the loop stops cleanly at end of file. The four lines print exactly as they were written.
Avoid the common alternative while (!inFile.eof()). The end-of-file flag is only set after a read has already failed, so that loop runs one extra time and usually prints the last line twice.
The second part opens a fresh stream, inFile2, so it starts from the beginning again. inFile2 >> word skips any whitespace, including newlines, and reads up to the next whitespace. That is why every word ends up on one line separated by spaces: the line breaks are treated as just more whitespace. Punctuation stays attached, so "Hello," and "World!" are separate words with their comma and exclamation mark.
Both streams are closed explicitly. They would also close themselves when they go out of scope.
The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <fstream> is there because it provides file stream classes (ofstream, ifstream). <string> is there because it provides string class for string operations. Leave one out and the compiler stops at the first name it does not recognize.
Understanding File Reading
ifstream Concept:
Reading Methods:
Opening File for Reading
Creating ifstream:
ifstream inFile("data.txt");
What happens here:
Checking Success:
if (inFile.is_open()) {
// File opened successfully
}
Reading Line by Line
Using getline():
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
What happens here:
Reading Word by Word
Using >> Operator:
string word;
while (inFile >> word) {
cout << word << " ";
}
What happens here:
When to Use Each Method
getline():
>> Operator:
Important Considerations
File Existence:
End of File:
File Paths:
return 0;
return 0; closes main and tells the operating system the program finished without an error.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why does the word-by-word output fit on one line?
Pick an answer to check it.
Question 2
What is wrong with while (!inFile.eof()) { getline(inFile, line); cout << line; }?
Pick an answer to check it.
Questions people ask
How do I read numbers from the file?
Use int x; while (inFile >> x) { ... }.
How do I go back to the start without reopening?
inFile.clear(); inFile.seekg(0);. clear() resets the end-of-file flag first.
How do I read the whole file into one string?
string s((istreambuf_iterator<char>(inFile)), istreambuf_iterator<char>());