Consider the following C++ code that reads from a file named data.txt containing the text "Hello World". What will be printed to the console?
#include <iostream> #include <fstream> #include <string> int main() { std::ifstream file("data.txt"); std::string word; while (file >> word) { std::cout << word << " "; } return 0; }
Think about how the extraction operator >> reads words separated by whitespace.
The extraction operator >> reads one word at a time, skipping whitespace. The code prints each word followed by a space, so the output is Hello World with a space between words.
Given the following C++ code, what will be the content of the file output.txt after running it?
#include <fstream> int main() { std::ofstream file("output.txt"); file << "Line1\n"; file << "Line2"; file.close(); return 0; }
Remember that \n is a newline character in C++ strings.
The code writes "Line1" followed by a newline, then "Line2" without newline. So the file content is two lines: first line "Line1", second line "Line2".
Look at this C++ code snippet intended to read a full line from a file. Why does it only read the first word?
#include <iostream> #include <fstream> #include <string> int main() { std::ifstream file("input.txt"); std::string line; file >> line; std::cout << line << std::endl; return 0; }
Think about the difference between operator>> and getline().
The extraction operator >> reads input until the first whitespace, so it only reads the first word. To read a full line, std::getline(file, line) should be used.
Which of the following code snippets will cause a compilation error when trying to open and write to a file?
Check the parameters required by open() method.
The open() method requires a filename as a parameter. Option D calls file.open() without arguments, causing a compilation error.
This C++ program reads lines from input.txt and writes only non-empty lines to output.txt. If input.txt contains 5 lines, where 2 lines are empty, how many lines will output.txt have?
#include <fstream> #include <string> int main() { std::ifstream infile("input.txt"); std::ofstream outfile("output.txt"); std::string line; while (std::getline(infile, line)) { if (!line.empty()) { outfile << line << "\n"; } } return 0; }
Count only lines that are not empty.
The code writes only lines that are not empty. Since 2 lines are empty out of 5, the output file will have 3 lines.