Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

get std string from file

#include <iostream>
#include <fstream>
#include <sstream>

using std::cout; using std::cerr;
using std::endl; using std::string;
using std::ifstream; using std::ostringstream;

string readFileIntoString(const string& path) {
    ifstream input_file(path);
    if (!input_file.is_open()) {
        cerr << "Could not open the file - '"
             << path << "'" << endl;
        exit(EXIT_FAILURE);
    }
    return string((std::istreambuf_iterator<char>(input_file)), std::istreambuf_iterator<char>());
}

int main()
{
    string filename("input.txt");
    string file_contents;

    file_contents = readFileIntoString(filename);
    cout << file_contents << endl;

    exit(EXIT_SUCCESS);
}
Source by www.delftstack.com #
 
PREVIOUS NEXT
Tagged: #std #string #file
ADD COMMENT
Topic
Name
5+1 =