Challenge - 5 Problems
File Input Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2: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; }
Attempts:
2 left
π‘ Hint
The program reads integers one by one and adds them.
β Incorrect
The program reads each integer from the file and adds it to sum. The numbers are 10, 20, and 30, so the sum is 60.
β Predict Output
intermediate2: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; }
Attempts:
2 left
π‘ Hint
Count how many lines the file has.
β Incorrect
The program counts lines using getline. The file has 3 lines, so it prints 3.
π§ Debug
advanced2: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; }
Attempts:
2 left
π‘ Hint
Check how eof() works in file streams.
β Incorrect
The eof() flag is set only after a failed read. Checking eof() before reading causes the loop to run one extra time, printing the last value again.
π Syntax
advanced2:00remaining
Identify the syntax error in file reading
Which option contains the correct syntax to open a file and read a single integer?
Attempts:
2 left
π‘ Hint
Check how ifstream is constructed and how to read data.
β Incorrect
Option C correctly constructs ifstream with filename and uses >> operator to read an integer. Others have syntax errors or wrong methods.
π Application
expert3:00remaining
Count words in a file
Which program correctly counts the number of words in
text.txt?Attempts:
2 left
π‘ Hint
Words are separated by whitespace and can be read with >> operator.
β Incorrect
Option A reads words one by one using >> operator and counts them correctly. Option A counts characters, not words. Option A counts spaces, which may be less accurate. Option A uses eof() incorrectly causing an extra count.