温馨提示×

C++怎么读取文件内容

c++
小亿
96
2024-01-12 10:04:19
栏目: 编程语言

在C++中,可以使用std::ifstream类来读取文件内容。下面是一个简单的示例代码:

#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;
}

在上述代码中,使用std::ifstream类打开文件,并使用std::getline()函数逐行读取文件内容。读取的每一行都被打印到标准输出中。最后,使用file.close()关闭文件。

请确保在运行代码之前,当前目录下存在一个名为example.txt的文件。

0