How do I read an entire file into a std::string in C++?

后端 未结 15 1933
余生分开走
余生分开走 2020-11-21 23:51

How do I read a file into a std::string, i.e., read the whole file at once?

Text or binary mode should be specified by the caller. The solution should b

15条回答
  •  被撕碎了的回忆
    2020-11-22 00:09

    #include 
    #include 
    #include 
    using namespace std;
    main(){
        fstream file;
        //Open a file
        file.open("test.txt");
        string copy,temp;
        //While loop to store whole document in copy string
        //Temp reads a complete line
        //Loop stops until temp reads the last line of document
        while(getline(file,temp)){
            //add new line text in copy
            copy+=temp;
            //adds a new line
            copy+="\n";
        }
        //Display whole document
        cout<

提交回复
热议问题