Bird
Raised Fist0
C++programming~20 mins

File input using ifstream in C++ - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
πŸŽ–οΈ
File Input Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Reading integers from a file
What is the output of this C++ program if the file numbers.txt contains the numbers 10 20 30?
C++
#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ifstream file("numbers.txt");
    int sum = 0, x;
    while (file >> x) {
        sum += x;
    }
    cout << sum << endl;
    return 0;
}
A0
B102030
C10 20 30
D60
Attempts:
2 left
πŸ’‘ Hint
The program reads integers one by one and adds them.
❓ Predict Output
intermediate
2:00remaining
Reading lines from a file
What will this program print if data.txt contains:
Hello
World
C++
C++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ifstream file("data.txt");
    string line;
    int count = 0;
    while (getline(file, line)) {
        count++;
    }
    cout << count << endl;
    return 0;
}
A3
BHello World C++
C0
D1
Attempts:
2 left
πŸ’‘ Hint
Count how many lines the file has.
πŸ”§ Debug
advanced
2:00remaining
Why does this file reading loop fail?
This code tries to read integers from input.txt and print them. Why does it print the last number twice?
C++
#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ifstream file("input.txt");
    int x;
    while (!file.eof()) {
        file >> x;
        cout << x << endl;
    }
    return 0;
}
ABecause cout prints the buffer twice
BBecause checking eof() before reading causes the last read to fail but still prints the old value
CBecause the variable x is not initialized
DBecause the file is empty
Attempts:
2 left
πŸ’‘ Hint
Check how eof() works in file streams.
πŸ“ Syntax
advanced
2:00remaining
Identify the syntax error in file reading
Which option contains the correct syntax to open a file and read a single integer?
Aifstream file; file.open = "data.txt"; int x; file >> x;
Bifstream file = "data.txt"; int x; file >> x;
Cifstream file("data.txt"); int x; file >> x;
Difstream file("data.txt"); int x; file.read(x);
Attempts:
2 left
πŸ’‘ Hint
Check how ifstream is constructed and how to read data.
πŸš€ Application
expert
3:00remaining
Count words in a file
Which program correctly counts the number of words in text.txt?
A
#include &lt;fstream&gt;
#include &lt;string&gt;
#include &lt;iostream&gt;
using namespace std;
int main() {
    ifstream file("text.txt");
    string word;
    int count = 0;
    while (file &gt;&gt; word) {
        count++;
    }
    cout &lt;&lt; count &lt;&lt; endl;
    return 0;
}
B
#include &lt;fstream&gt;
#include &lt;string&gt;
#include &lt;iostream&gt;
using namespace std;
int main() {
    ifstream file("text.txt");
    string line;
    int count = 0;
    while (getline(file, line)) {
        count += line.size();
    }
    cout &lt;&lt; count &lt;&lt; endl;
    return 0;
}
C
#include &lt;fstream&gt;
#include &lt;string&gt;
#include &lt;iostream&gt;
using namespace std;
int main() {
    ifstream file("text.txt");
    char c;
    int count = 0;
    while (file.get(c)) {
        if (c == ' ') count++;
    }
    cout &lt;&lt; count &lt;&lt; endl;
    return 0;
}
D
#include &lt;fstream&gt;
#include &lt;string&gt;
#include &lt;iostream&gt;
using namespace std;
int main() {
    ifstream file("text.txt");
    int count = 0;
    while (!file.eof()) {
        string word;
        file &gt;&gt; word;
        count++;
    }
    cout &lt;&lt; count &lt;&lt; endl;
    return 0;
}
Attempts:
2 left
πŸ’‘ Hint
Words are separated by whitespace and can be read with >> operator.

Practice

(1/5)
1. What is the primary purpose of ifstream in C++?
easy
A. To write data to a file
B. To read data from a file
C. To create a new file
D. To delete a file

Solution

  1. Step 1: Understand the role of ifstream

    ifstream stands for input file stream and is used to read data from files.
  2. Step 2: Differentiate from other file streams

    ofstream is used for writing, not reading. Creating or deleting files is not handled by ifstream.
  3. Final Answer:

    To read data from a file -> Option B
  4. Quick Check:

    ifstream = read file [OK]
Hint: Remember: ifstream = input (read) file stream [OK]
Common Mistakes:
  • Confusing ifstream with ofstream
  • Thinking ifstream writes to files
  • Assuming ifstream creates files
2. Which of the following is the correct way to open a file named data.txt for reading using ifstream?
easy
A. ifstream file = open("data.txt");
B. std::ifstream file.open("data.txt");
C. std::ifstream file("data.txt");
D. ifstream file("data.txt").open();

Solution

  1. Step 1: Recall correct syntax for opening files with ifstream

    The correct way is to create an ifstream object and pass the filename as a constructor argument: std::ifstream file("data.txt");
  2. Step 2: Identify incorrect syntax in other options

    std::ifstream file.open("data.txt"); incorrectly uses dot notation with constructor. ifstream file = open("data.txt"); uses a non-existent open function. ifstream file("data.txt").open(); tries to call open() after constructor incorrectly.
  3. Final Answer:

    std::ifstream file("data.txt"); -> Option C
  4. Quick Check:

    Constructor with filename = correct open [OK]
Hint: Use constructor with filename to open file [OK]
Common Mistakes:
  • Calling open() on constructor line
  • Using open() as a free function
  • Mixing syntax of ifstream and other file functions
3. What will be the output of the following code if the file numbers.txt contains the numbers 10 and 20 on separate lines?
std::ifstream file("numbers.txt");
int a, b;
file >> a >> b;
std::cout << a + b << std::endl;
file.close();
medium
A. 30
B. 1020
C. 10 20
D. Compilation error

Solution

  1. Step 1: Understand file reading with >> operator

    The code reads two integers from the file into variables a and b. The file contains 10 and 20 on separate lines, so a=10 and b=20.
  2. Step 2: Calculate the output of the sum

    The code outputs a + b, which is 10 + 20 = 30.
  3. Final Answer:

    30 -> Option A
  4. Quick Check:

    10 + 20 = 30 [OK]
Hint: >> reads values; sum them for output [OK]
Common Mistakes:
  • Thinking >> concatenates numbers as strings
  • Expecting output as '10 20' instead of sum
  • Forgetting to close the file
4. Identify the error in the following code snippet:
std::ifstream file;
file.open("data.txt");
int x;
file >> x;
file.close();
medium
A. File is not opened before reading
B. File should not be closed manually
C. Incorrect syntax for reading integer
D. Missing check if file opened successfully

Solution

  1. Step 1: Check file opening and reading steps

    The code opens the file and reads an integer correctly. Syntax is valid.
  2. Step 2: Identify missing safety check

    There is no check to confirm if the file opened successfully before reading. This can cause runtime errors if the file doesn't exist.
  3. Final Answer:

    Missing check if file opened successfully -> Option D
  4. Quick Check:

    Always check file.open() success before reading [OK]
Hint: Always verify file opened before reading [OK]
Common Mistakes:
  • Ignoring file open failure
  • Assuming file always exists
  • Not closing the file (though here it is closed)
5. You want to read all integers from a file values.txt until the end of the file. Which code snippet correctly does this using ifstream?
hard
A. std::ifstream file("values.txt"); int num; while (file >> num) { std::cout << num << std::endl; } file.close();
B. std::ifstream file("values.txt"); int num; while (!file.eof()) { file >> num; std::cout << num << std::endl; } file.close();
C. std::ifstream file("values.txt"); int num; do { file >> num; std::cout << num << std::endl; } while (!file.fail()); file.close();
D. std::ifstream file("values.txt"); int num; while (file.good()) { file >> num; std::cout << num << std::endl; } file.close();

Solution

  1. Step 1: Understand correct loop condition for reading

    Using while (file >> num) reads integers and stops when reading fails (end of file or error).
  2. Step 2: Analyze why other options are incorrect

    std::ifstream file("values.txt"); int num; while (!file.eof()) { file >> num; std::cout << num << std::endl; } file.close(); uses while (!file.eof()) which can cause reading invalid data after EOF. std::ifstream file("values.txt"); int num; do { file >> num; std::cout << num << std::endl; } while (!file.fail()); file.close(); uses do-while with fail check but prints invalid data after failure. std::ifstream file("values.txt"); int num; while (file.good()) { file >> num; std::cout << num << std::endl; } file.close(); uses file.good() which may not detect EOF correctly before reading.
  3. Final Answer:

    std::ifstream file("values.txt"); int num; while (file >> num) { std::cout << num << std::endl; } file.close(); -> Option A
  4. Quick Check:

    Use while(file >> var) to read until EOF [OK]
Hint: Use while(file >> var) to read safely till EOF [OK]
Common Mistakes:
  • Using while(!file.eof()) causing extra reads
  • Printing data after failed read
  • Using file.good() incorrectly for loop condition
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard