Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

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.

BeginnerFile Handling ProgramsExample 2 of 6
read-from-file.cpp
1#include <iostream>
2#include <fstream>
3#include <string>
4using namespace std;
5
6int main() {
7 // Open file for reading
8 ifstream inFile("data.txt");
9
10 if (inFile.is_open()) {
11 string line;
12
13 cout << "Reading file line by line:" << endl;
14 while (getline(inFile, line)) {
15 cout << line << endl;
16 }
17
18 inFile.close();
19 } else {
20 cout << "Error: Unable to open file for reading." << endl;
21 }
22
23 // Alternative: Read word by word
24 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 }
34
35 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. 1

    Open data.txt with ifstream and check is_open().

  2. 2

    getline in a loop and print each line.

  3. 3

    Close the stream.

  4. 4

    Open a second stream and read with >> word.

  5. 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:

Input file stream
Used for reading from files
Similar to cin but reads from file
File must exist to read

Reading Methods:

getline(): reads entire line
>> operator: reads word by word
read(): reads binary data

Opening File for Reading

Creating ifstream:

ifstream inFile("data.txt");

What happens here:

Creates ifstream object
Opens file "data.txt" for reading
File must exist
Returns error if file not found

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:

getline() reads until newline
Returns false at end of file
Preserves line structure
Reads entire line including spaces

Reading Word by Word

Using >> Operator:

string word;

while (inFile >> word) {

cout << word << " ";

}

What happens here:

>> operator reads until whitespace
Stops at space, tab, newline
Skips whitespace automatically
Returns false at end of file

When to Use Each Method

getline():

Preserve line structure
Read formatted lines
Process line by line
Keep spaces in line

>> Operator:

Read individual words
Skip whitespace
Parse space-separated data
Process tokens

Important Considerations

File Existence:

File must exist to read
Check is_open() before reading
Handle file not found errors
Provide user feedback

End of File:

Loop until end of file
getline() and >> return false at EOF
File pointer moves automatically
Don't read past EOF

File Paths:

Relative or absolute paths
Check file permissions
Handle access errors

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>());