I currently have a little program here that will rewrite the contents of a .txt file as a string.
However I’d like to gather all the contents of the file as a single string, how can I go about this?
#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;
}
}
The libstdc++ guys have a good discussion of how to do this with
rdbuf.The important part is:
I know, you asked about putting the contents into a
string. You can do that by makingoutastd::stringstream. Or you can just add it to astd::stringincrementally withstd::getline: