0
0
C++programming~10 mins

File output using ofstream in C++ - Interactive Code Practice

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

Complete the code to include the header needed for file output.

C++
#include [1]

int main() {
    return 0;
}
Drag options to blanks, or click blank then click option'
A<vector>
B<iostream>
C<fstream>
D<string>
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Including instead of
Forgetting to include any header for file output
2fill in blank
medium

Complete the code to create an ofstream object named 'file' that opens 'output.txt'.

C++
std::[1] file("output.txt");
Drag options to blanks, or click blank then click option'
Aifstream
Bofstream
Cfstream
Diostream
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using ifstream instead of ofstream
Using fstream without specifying mode
3fill in blank
hard

Fix the error in the code to write 'Hello, file!' to the file.

C++
std::ofstream file("output.txt");
file [1] "Hello, file!";
file.close();
Drag options to blanks, or click blank then click option'
A<<
B==
C=
D>>
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using >> instead of <<
Using = to assign instead of writing
4fill in blank
hard

Fill both blanks to check if the file was opened successfully and print a message.

C++
std::ofstream file("output.txt");
if (file.[1]()) {
    std::cout << "File opened successfully." << std::endl;
} else {
    std::cout << "Failed to open file." << std::endl;
}
Drag options to blanks, or click blank then click option'
Aclose
Bopen
Cfail
Dis_open
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using open() instead of is_open() in the if condition
Using fail() incorrectly
5fill in blank
hard

Fill all three blanks to write multiple lines to a file using a loop.

C++
std::ofstream file("output.txt");
for (int [1] = 1; i <= 3; [2]) {
    file [3] "Line " << i << std::endl;
}
file.close();
Drag options to blanks, or click blank then click option'
Ai
B++i
C<<
D--i
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using wrong variable name in loop
Using --i which decrements instead of increments
Using >> instead of << to write