Bird
Raised Fist0
C++programming~20 mins

Reading and writing files in C++ - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
πŸŽ–οΈ
File Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this file reading code?

Consider the following C++ code that reads from a file named data.txt containing the text "Hello World". What will be printed to the console?

C++
#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream file("data.txt");
    std::string word;
    while (file >> word) {
        std::cout << word << " ";
    }
    return 0;
}
AHello\nWorld\n
BHelloWorld
CHello World
D
Hello
World
Attempts:
2 left
πŸ’‘ Hint

Think about how the extraction operator >> reads words separated by whitespace.

❓ Predict Output
intermediate
2:00remaining
What does this file writing code produce in the file?

Given the following C++ code, what will be the content of the file output.txt after running it?

C++
#include <fstream>

int main() {
    std::ofstream file("output.txt");
    file << "Line1\n";
    file << "Line2";
    file.close();
    return 0;
}
ALine1\nLine2
B
Line1
Line2
CLine1 Line2
DLine1\n\nLine2
Attempts:
2 left
πŸ’‘ Hint

Remember that \n is a newline character in C++ strings.

πŸ”§ Debug
advanced
2:00remaining
Why does this file reading code fail to read the entire line?

Look at this C++ code snippet intended to read a full line from a file. Why does it only read the first word?

C++
#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream file("input.txt");
    std::string line;
    file >> line;
    std::cout << line << std::endl;
    return 0;
}
ABecause operator >> reads only until the first whitespace, not the whole line.
BBecause the file is not opened in binary mode.
CBecause the string variable is not initialized.
DBecause the file stream is not flushed before reading.
Attempts:
2 left
πŸ’‘ Hint

Think about the difference between operator>> and getline().

πŸ“ Syntax
advanced
2:00remaining
Which option causes a compilation error?

Which of the following code snippets will cause a compilation error when trying to open and write to a file?

A
#include &lt;fstream&gt;
int main() {
    std::ofstream file("test.txt");
    file &lt;&lt; "Hello";
    return 0;
}
B
#include &lt;fstream&gt;
int main() {
    std::ofstream file;
    file.open("test.txt");
    file &lt;&lt; "Hello";
    return 0;
}
C
#include &lt;fstream&gt;
int main() {
    std::ofstream file("test.txt");
    file.write("Hello", 5);
    return 0;
}
D
#include &lt;fstream&gt;
int main() {
    std::ofstream file;
    file.open();
    file &lt;&lt; "Hello";
    return 0;
}
Attempts:
2 left
πŸ’‘ Hint

Check the parameters required by open() method.

πŸš€ Application
expert
2:00remaining
How many lines will be in the output file after running this code?

This C++ program reads lines from input.txt and writes only non-empty lines to output.txt. If input.txt contains 5 lines, where 2 lines are empty, how many lines will output.txt have?

C++
#include <fstream>
#include <string>

int main() {
    std::ifstream infile("input.txt");
    std::ofstream outfile("output.txt");
    std::string line;
    while (std::getline(infile, line)) {
        if (!line.empty()) {
            outfile << line << "\n";
        }
    }
    return 0;
}
A3
B0
C2
D5
Attempts:
2 left
πŸ’‘ Hint

Count only lines that are not empty.

Practice

(1/5)
1. What is the primary purpose of using 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, which is used to read data from files.
  2. Step 2: Differentiate from ofstream

    ofstream is used to write data to files, so it is not the correct answer here.
  3. Final Answer:

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

    ifstream = read file [OK]
Hint: Remember 'i' in ifstream means input (read) [OK]
Common Mistakes:
  • Confusing ifstream with ofstream
  • Thinking ifstream creates or deletes files
  • Mixing input and output streams
2. Which of the following is the correct way to open a file named data.txt for writing using ofstream?
easy
A. ofstream file.open("data.txt");
B. ifstream file("data.txt");
C. file.open(ofstream, "data.txt");
D. ofstream file("data.txt");

Solution

  1. Step 1: Recognize correct ofstream syntax

    To open a file for writing, you create an ofstream object and pass the filename to its constructor.
  2. Step 2: Check other options for syntax errors

    ifstream file("data.txt"); uses ifstream which is for reading, not writing. ofstream file.open("data.txt"); incorrectly calls open as a constructor. file.open(ofstream, "data.txt"); has wrong parameter order and syntax.
  3. Final Answer:

    ofstream file("data.txt"); -> Option D
  4. Quick Check:

    Correct ofstream constructor usage = ofstream file("data.txt"); [OK]
Hint: Use constructor with filename to open file for writing [OK]
Common Mistakes:
  • Using ifstream instead of ofstream for writing
  • Calling open() incorrectly
  • Passing wrong arguments to open()
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
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. Since the file has 10 and 20 on separate lines, a = 10 and b = 20.
  2. Step 2: Calculate the output

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

    30 -> Option A
  4. Quick Check:

    10 + 20 = 30 [OK]
Hint: >> reads values as numbers, not strings [OK]
Common Mistakes:
  • Thinking >> concatenates numbers as strings
  • Forgetting to close the file
  • Assuming output is the first number only
4. Identify the error in the following code snippet that tries to write "Hello" to a file named output.txt:
std::ofstream file;
file << "Hello";
file.open("output.txt");
file.close();
medium
A. File should be closed before opening
B. Missing semicolon after file.open()
C. File is opened after writing to it
D. ofstream cannot write strings

Solution

  1. Step 1: Check order of operations

    The code tries to write to the file before opening it, which is incorrect because the file must be opened first.
  2. Step 2: Confirm other options

    Missing semicolon after file.open() is wrong because semicolons are present. ofstream cannot write strings is false; ofstream can write strings. File should be closed before opening is incorrect; you cannot close before opening.
  3. Final Answer:

    File is opened after writing to it -> Option C
  4. Quick Check:

    Open file before writing [OK]
Hint: Always open file before writing or reading [OK]
Common Mistakes:
  • Writing before opening the file
  • Confusing order of open and close
  • Assuming ofstream can't write strings
5. You want to read integers from a file input.txt and write only the even numbers to even.txt. Which code snippet correctly implements this?
hard
A. std::ifstream inFile("input.txt"); std::ofstream outFile("even.txt"); int num; while (inFile >> num) { if (num % 2 == 0) { outFile << num << '\n'; } } inFile.close(); outFile.close();
B. std::ofstream inFile("input.txt"); std::ifstream outFile("even.txt"); int num; while (inFile >> num) { if (num % 2 == 0) { outFile << num << '\n'; } } inFile.close(); outFile.close();
C. std::ifstream inFile; std::ofstream outFile; inFile.open("input.txt"); outFile.open("even.txt"); int num; while (inFile >> num) { if (num % 2 == 1) { outFile << num << '\n'; } } inFile.close(); outFile.close();
D. std::ifstream inFile("input.txt"); std::ofstream outFile("even.txt"); int num; while (!inFile.eof()) { inFile >> num; if (num % 2 == 0) { outFile << num << '\n'; } } inFile.close(); outFile.close();

Solution

  1. Step 1: Check correct stream types and file opening

    std::ifstream inFile("input.txt"); std::ofstream outFile("even.txt"); int num; while (inFile >> num) { if (num % 2 == 0) { outFile << num << '\n'; } } inFile.close(); outFile.close(); correctly uses ifstream to read and ofstream to write, opening files in constructors.
  2. Step 2: Verify reading loop and condition

    std::ifstream inFile("input.txt"); std::ofstream outFile("even.txt"); int num; while (inFile >> num) { if (num % 2 == 0) { outFile << num << '\n'; } } inFile.close(); outFile.close(); uses while (inFile >> num) which safely reads integers until EOF. It writes only even numbers (num % 2 == 0) to output.
  3. Step 3: Identify errors in other options

    std::ofstream inFile("input.txt"); std::ifstream outFile("even.txt"); int num; while (inFile >> num) { if (num % 2 == 0) { outFile << num << '\n'; } } inFile.close(); outFile.close(); swaps stream types incorrectly. std::ifstream inFile; std::ofstream outFile; inFile.open("input.txt"); outFile.open("even.txt"); int num; while (inFile >> num) { if (num % 2 == 1) { outFile << num << '\n'; } } inFile.close(); outFile.close(); writes odd numbers, not even. std::ifstream inFile("input.txt"); std::ofstream outFile("even.txt"); int num; while (!inFile.eof()) { inFile >> num; if (num % 2 == 0) { outFile << num << '\n'; } } inFile.close(); outFile.close(); uses while (!inFile.eof()) which can cause reading errors.
  4. Final Answer:

    Option A code snippet -> Option A
  5. Quick Check:

    Correct streams + safe read loop + even check = std::ifstream inFile("input.txt"); std::ofstream outFile("even.txt"); int num; while (inFile >> num) { if (num % 2 == 0) { outFile << num << '\n'; } } inFile.close(); outFile.close(); [OK]
Hint: Use while(inFile >> num) and check even with num % 2 == 0 [OK]
Common Mistakes:
  • Swapping ifstream and ofstream
  • Using eof() in loop condition
  • Writing odd numbers instead of even
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