text file c++ to string 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");
  //Two ways:
  
  //Assign it at initialization
  string content( (istreambuf_iterator<char>(ifs) ),
                  (istreambuf_iterator<char>()    ) );
  
  //Assign it after initialization
  content.assign( (istreambuf_iterator<char>(ifs) ),
                  (istreambuf_iterator<char>()    ) );
  return 0;
}

Tags:

Cpp Example