text file to string cpp code example
Example 1: c++ file to string
string filetostring(){
ifstream file("file", ios::binary);
string fileStr;
istreambuf_iterator<char> inputIt(file), emptyInputIt;
back_insert_iterator<string> stringInsert(fileStr);
copy(inputIt, emptyInputIt, stringInsert);
return fileStr;
}
Example 2: c++ read text file to string
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream ifs("myfile.txt");
string content( (istreambuf_iterator<char>(ifs) ),
(istreambuf_iterator<char>() ) );
content.assign( (istreambuf_iterator<char>(ifs) ),
(istreambuf_iterator<char>() ) );
return 0;
}