2

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!

Ziezi
  • 6,049
  • 3
  • 34
  • 45
Cody Richardson
  • 147
  • 2
  • 15
  • 1
    possible duplicate of [Read whole ASCII file into C++ std::string](http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring) – Jonathan Potter Mar 28 '15 at 03:14
  • Why exactly haven't you tested it? It's the easiest way to know if it works or not :) – Kelm Mar 28 '15 at 03:15
  • 2
    @Kelm: But not necessarily the most reliable way. "Appearing to work" can be very different than "actually working". Especially in a language with so much undefined, unspecified and implementation defined behavior. – Benjamin Lindley Mar 28 '15 at 04:31

3 Answers3

1

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;
}
Ziezi
  • 6,049
  • 3
  • 34
  • 45
  • Thank you, this is working marvelously. I changed the vector to just a string, then instead of push_back, i appended line to it. Thanks! – Cody Richardson Mar 28 '15 at 03:30
1

There is a standard way:

std::ifstream     file("myfilename.txt");
std::stringstream buffer;
buffer << file.rdbuf();

std::string content( buffer.str() );

References

fjardon
  • 7,510
  • 19
  • 29
0

try this one

#include <fstream>
#include <cstdlib>
std::string readText(const char* fileName)
{
    std::ifstream file(fileName);

    if (!file.good())
    {
        std::cout << "file fail to load..." << fileName;
        exit(1);
    }

    return std::string(std::istreambuf_iterator<char>(file),        std::istreambuf_iterator<char>());

}
Cody Richardson
  • 147
  • 2
  • 15
Ahmed
  • 59
  • 7