0
0
C++programming~10 mins

Reading and writing files 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 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'
Aclose
Bwrite
Copen
Dread
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'read' instead of 'open' to open the file.
Trying to write before opening the file.
2fill in blank
medium

Complete 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'
Aline
Bfile
Ctext
Dinput
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Passing the file stream instead of the string variable.
Using an undeclared variable.
3fill in blank
hard

Fix 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'
A<<
B+
C>>
D=
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using '+' which tries to add instead of writing.
Using '>>' which is for input streams.
4fill in blank
hard

Fill 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'
Aword
Bfile
Clength
Dline
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using the file stream as a key instead of the word.
Using an undefined variable.
5fill in blank
hard

Fill 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'
Aword
C>
D<
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using different variable names in the loop and condition.
Using '<' instead of '>' in the condition.