Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to open a file named "data.txt" for reading.
C++
#include <fstream> #include <iostream> int main() { std::ifstream file; file.[1]("data.txt"); if (!file) { std::cout << "Failed to open file." << std::endl; } return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using 'close' instead of 'open' to open the file.
Trying to use 'read' or 'write' directly to open the file.
β Incorrect
The open function is used to open a file with ifstream.
2fill in blank
mediumComplete the code to read a single word from the file into the variable 'word'.
C++
#include <fstream> #include <iostream> #include <string> int main() { std::ifstream file("data.txt"); std::string word; if (file >> [1]) { std::cout << "Read word: " << word << std::endl; } return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Trying to read into 'input' or 'file' which are not variables for storing the word.
Using 'data' which is not declared.
β Incorrect
We read into the variable word using the extraction operator.
3fill in blank
hardFix the error in the code to properly check if the file was opened successfully.
C++
#include <fstream> #include <iostream> int main() { std::ifstream file("data.txt"); if ([1]) { std::cout << "File opened successfully." << std::endl; } else { std::cout << "Failed to open file." << std::endl; } return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using '!file' which checks if the file failed to open, but logic is reversed.
Using '!file.is_open()' which is true when file is not open.
β Incorrect
The is_open() method returns true if the file is open.
4fill in blank
hardFill both blanks to read all words from the file and print them.
C++
#include <fstream> #include <iostream> #include <string> int main() { std::ifstream file("data.txt"); std::string [1]; while (file >> [2]) { std::cout << [2] << std::endl; } return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using different variable names for declaration and reading.
Using 'file' as a variable to store words.
β Incorrect
The variable word is used to store each word read from the file.
5fill in blank
hardFill all three blanks to open a file, read integers, and sum them.
C++
#include <fstream> #include <iostream> int main() { std::ifstream [1]("numbers.txt"); int [2], sum = 0; while ([1] >> [2]) { sum += [2]; } std::cout << "Sum: " << sum << std::endl; return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using different names for the file stream in declaration and reading.
Using 'number' instead of 'num' for the integer variable.
β Incorrect
The ifstream object is named file, and the integer variable is num. The same file is used to read integers.