How to read the content of a text file in C++?
In C++, you can use the ifstream class to read the contents of a text file. Here is a simple example:
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("example.txt"); // 打开文件
if (file.is_open()) { // 检查文件是否成功打开
std::string line;
while (std::getline(file, line)) { // 逐行读取文件内容
std::cout << line << std::endl; // 输出每一行的内容
}
file.close(); // 关闭文件
} else {
std::cout << "无法打开文件" << std::endl;
}
return 0;
}
In the code above, an input file stream object “file” is created using the std::ifstream class, and the file name to be opened is passed to it through the constructor.
Then, you can use the is_open() function to check if the file was successfully opened. If the file was successfully opened, you can use the std::getline() function to read the content of the file line by line.
Finally, use std::cout to display the content of each line and close the file using the close() function after reading. If the file cannot be opened, output the corresponding error message.
Note: When actually using it, be sure to change “example.txt” to the appropriate file name based on the file’s path and name.