0
0
C++programming~10 mins

Why file handling is required in C++ - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to open a file for reading.

C++
#include <fstream>
int main() {
    std::ifstream file[1];
    return 0;
}
Drag options to blanks, or click blank then click option'
A("data.txt")
B["data.txt"]
C{data.txt}
D<data.txt>
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using square brackets or braces instead of parentheses.
Not passing the filename as a string.
2fill in blank
medium

Complete the code to write text to a file.

C++
#include <fstream>
int main() {
    std::ofstream file("output.txt");
    file[1] "Hello, file!";
    file.close();
    return 0;
}
Drag options to blanks, or click blank then click option'
A+=
B>>
C<<
D=
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using >> instead of << for writing.
Using assignment operator = which is invalid here.
3fill in blank
hard

Fix the error in the code to read a line from a file.

C++
#include <fstream>
#include <string>
int main() {
    std::ifstream file("input.txt");
    std::string line;
    if (file.is_open()) {
        std::getline(file[1], line);
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
A)
B(
C;
D]
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Missing closing parenthesis.
Using brackets or semicolon instead of closing parenthesis.
4fill in blank
hard

Fill both blanks to create a file and write multiple lines.

C++
#include <fstream>
int main() {
    std::ofstream file[1];
    file << "Line 1" << std::endl[2];
    file.close();
    return 0;
}
Drag options to blanks, or click blank then click option'
A("log.txt")
B("data.txt")
C<<
D>>
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using wrong filename or wrong operator for writing.
Using >> instead of << for writing.
5fill in blank
hard

Fill both blanks to read from a file and print its content.

C++
#include <fstream>
#include <iostream>
#include <string>
int main() {
    std::ifstream file[1];
    std::string line;
    while (std::getline(file, line)) {
        std::cout[2] line << std::endl;;
    }
    file.close();
    return 0;
}
Drag options to blanks, or click blank then click option'
A("readme.txt")
B<<
C;
D>>
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using >> instead of << for output.
Missing semicolon at the end of the output statement.