How can C++ read the content of a file?

“In C++, you can use the std::ifstream class to read file contents. Here is a simple example code:”

#include <iostream>
#include <fstream>

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, a file is opened using the std::ifstream class and its content is read line by line using the std::getline() function. Each line read is then printed to the standard output. Finally, the file is closed using file.close().

Please make sure that there is a file named example.txt in the current directory before running the code.

bannerAds