c++ read text file 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;
}
Example 3: read text from file c++
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ifstream myReadFile;
myReadFile.open("text.txt");
char output[100];
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
myReadFile >> output;
cout<<output;
}
}
myReadFile.close();
return 0;
}