将 ASCII 文件读取到C++ std::string 中的最简单方法是什么?

What is the easiest way of reading a ASCII file into an C++ std::string?

本文关键字:最简单 方法 是什么 string 读取 文件 C++ std ASCII      更新时间:2023-10-16

很多时候,需要将整个文件内容读入 std::string。哪种方法最简单?

假设我们有一个文件"test.txt"。通常,我发现这样做的最佳方法是使用以下代码:

#include <iostream>
#include <sstream>
#include <fstream>
int main()
{
    std::ifstream ifs("test.txt");
    std::stringstream buffer;
    buffer << ifs.rdbuf();
    std::cout << buffer.str() << std::endl;
    return 0;
}