Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
π‘ Hint
Common Mistakes
Including instead of
Forgetting to include any header for file output
β Incorrect
The
2fill in blank
mediumComplete 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'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using ifstream instead of ofstream
Using fstream without specifying mode
β Incorrect
ofstream is used to write to files.
3fill in blank
hardFix 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'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using >> instead of <<
Using = to assign instead of writing
β Incorrect
The insertion operator << is used to write data to the file stream.
4fill in blank
hardFill 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'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using open() instead of is_open() in the if condition
Using fail() incorrectly
β Incorrect
The is_open() function checks if the file stream is open.
5fill in blank
hardFill 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'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using wrong variable name in loop
Using --i which decrements instead of increments
Using >> instead of << to write
β Incorrect
Use 'i' as the loop variable, increment it with ++i, and write to file using << operator.