Complete the code to open a file named "data.txt" for reading.
#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; }
The open function is used to open a file with ifstream.
Complete the code to read a single word from the file into the variable 'word'.
#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; }
We read into the variable word using the extraction operator.
Fix the error in the code to properly check if the file was opened successfully.
#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; }
The is_open() method returns true if the file is open.
Fill both blanks to read all words from the file and print them.
#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; }
The variable word is used to store each word read from the file.
Fill all three blanks to open a file, read integers, and sum them.
#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; }
The ifstream object is named file, and the integer variable is num. The same file is used to read integers.
