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

rec*_*gle 0 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;


    }


}
Run Code Online (Sandbox Code Playgroud)

Ben*_*ley 6

#include <sstream>
#include <string>

std::string read_whole_damn_thing(std::istream & is)
{
    std::ostringstream oss;
    oss << is.rdbuf();
    return oss.str();
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*ger 5

声明一个字符串和一个缓冲区然后用while而不是EOF循环读取该文件并将缓冲区添加到字符串.