Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to open a file for writing.
C++
#include <fstream> int main() { std::ofstream file; file.[1]("output.txt"); file << "Hello, file!"; file.close(); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using 'read' instead of 'open' to open the file.
Trying to write before opening the file.
β Incorrect
The open function is used to open a file stream in C++.
2fill in blank
mediumComplete the code to read a line from a file.
C++
#include <fstream> #include <string> #include <iostream> int main() { std::ifstream file("input.txt"); std::string line; if (std::getline(file, [1])) { std::cout << line << std::endl; } file.close(); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Passing the file stream instead of the string variable.
Using an undeclared variable.
β Incorrect
The std::getline function reads a line into the variable passed as the second argument, here line.
3fill in blank
hardFix the error in the code to write numbers to a file.
C++
#include <fstream> int main() { std::ofstream file("numbers.txt"); for (int i = 1; i <= 5; i++) { file << i [1] " "; } file.close(); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using '+' which tries to add instead of writing.
Using '>>' which is for input streams.
β Incorrect
To write to a file stream, use the insertion operator <<.
4fill in blank
hardFill both blanks to create a map of word lengths from a file.
C++
#include <fstream> #include <string> #include <map> int main() { std::ifstream file("words.txt"); std::map<std::string, int> wordLengths; std::string word; while (file >> [1]) { wordLengths[[2]] = word.length(); } file.close(); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using the file stream as a key instead of the word.
Using an undefined variable.
β Incorrect
The variable word is used to read each word and as the key in the map.
5fill in blank
hardFill all three blanks to write only words longer than 3 characters to a file.
C++
#include <fstream> #include <string> #include <vector> int main() { std::vector<std::string> words = {"cat", "house", "dog", "elephant"}; std::ofstream file("long_words.txt"); for (const auto& [1] : words) { if ([2].length() [3] 3) { file << word << std::endl; } } file.close(); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using different variable names in the loop and condition.
Using '<' instead of '>' in the condition.
β Incorrect
The loop variable is word. We check if word.length() is greater than 3 to write it.