温馨提示×

标准C++中怎样读取整个文本文件到string中

c++
小亿
117
2023-12-20 14:06:30
栏目: 编程语言

在标准 C++ 中,可以使用 `` 头文件中的 `std::ifstream` 类来读取整个文本文件并将其存储到 `std::string` 对象

中。以下是读取文本文件到 `std::string` 的基本示例:

#include 
#include 
#include 
int main() {
    std::ifstream file("filename.txt"); // 替换为要读取的文件名
    if (file) { // 检查文件是否成功打开
        std::string content((std::istreambuf_iterator(file)),
                            std::istreambuf_iterator());
        std::cout << "File content: " << content << std::endl;
    } else {
        std::cerr << "Failed to open the file." << std::endl;
    }
    return 0;
}

在上述示例中,我们首先创建一个 `std::ifstream` 对象,并将要读取的文件名作为参数传递给构造函数。然后,我们检查文

件是否成功打开,并使用 `std::istreambuf_iterator` 将文件内容迭代读入 `std::string` 对象中。最后,我们输出读取到的文

件内容。

请确保将代码中的 `"filename.txt"` 替换为您实际要读取的文件的路径和名称。另外,请注意处理文件打开失败的情况,以

便进行适当的错误处理。

0