c++ - 将 .txt 文件的内容收集为字符串,C++

标签 c++ string file-io text-files file-read

我目前有一个小程序可以将 .txt 文件的内容重写为字符串。

但是我想将文件的所有内容收集为一个字符串,我该怎么做呢?

#include <iostream>
#include <fstream>
#include <string>


using namespace std;


int main () {
    string file_name ; 


    while (1 == 1){
        cout << "Input the directory or name of the file you would like to alter:" << endl;
        cin >>  file_name ;


        ofstream myfile ( file_name.c_str() );
        if (myfile.is_open())
        {
        myfile << "123abc";

        myfile.close();
        }
        else cout << "Unable to open file" << endl;


    }


}

最佳答案

#include <sstream>
#include <string>

std::string read_whole_damn_thing(std::istream & is)
{
    std::ostringstream oss;
    oss << is.rdbuf();
    return oss.str();
}

关于c++ - 将 .txt 文件的内容收集为字符串,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4084751/

相关文章:

c++ - 将 double 字符串转换为 double vector 的最佳方法是什么?

string - PHP - T_STRING 的含义

python - 如何检查变量的类型是否为字符串?

python - 在 python 中读取二进制文件时跳过第一个字节

c++ - string::erase 不接受迭代器?

c++ - 将 std::initializer_list 插入 std::map

c++ - 错误 LNK2005 对象已定义

java - 从android中的外部存储器读取android中的大文件(~15MB)

c++ - 如何使用 C++ 将 utf-8 字符写入文件

c++ - 如何在 string_view 中推断出悬空指针?