Q:

Set string to file contents c++

I was wanting to know if there was a simple way to set a std::string equal to the contents of a file in C++. So far, I was thinking something like this: (although I haven't tested it, so I don't know if it will work)
#include <fstream>
#include <string>

int main(int argc, char *argv[]){

    fstream in("file.txt");
    string str;

    str = in;

    return 0;
}

Is this a way to accomplish this? If not, is there a simple way to do so? Thanks!

A:

Here is one possible solution using vector<string>, each element is a line.
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    // vector that will store all the file lines
    vector<string> textLines;  

    // string holding one line
    string line;  

    // attach input stream to file    
    ifstream inputFile("data.txt");

    // test stream status   
    if(!inputFile)
    {
        std::cerr << "Can't open input file!\n";
    }

    // read the text line by line
    while(getline(inputFile, line))
    {
        // store each line as vector element
        textLines.push_back(line);
    }

    // optional (stream object destroyed at end of function scope)
    inputFile.close();

    return 0;
}

