Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using square brackets or braces instead of parentheses.
Not passing the filename as a string.
β Incorrect
To open a file in C++, you use parentheses with the filename as a string.
2fill in blank
mediumComplete 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'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using >> instead of << for writing.
Using assignment operator = which is invalid here.
β Incorrect
To write to a file stream, use the insertion operator <<.
3fill in blank
hardFix 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'
Attempts:
3 left
π‘ Hint
Common Mistakes
Missing closing parenthesis.
Using brackets or semicolon instead of closing parenthesis.
β Incorrect
The getline function requires the file stream as the first argument inside parentheses.
4fill in blank
hardFill 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'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using wrong filename or wrong operator for writing.
Using >> instead of << for writing.
β Incorrect
Use parentheses with filename to open file and << operator to write lines.
5fill in blank
hardFill 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'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using >> instead of << for output.
Missing semicolon at the end of the output statement.
β Incorrect
Open file with filename in parentheses, use << to print, and end statement with semicolon.