Search code examples
c++fileinputstreamstringstreamstring-parsingstdstring

Reading a file into memory C++: Is there a getline() for std::strings


I was asked to update my code that reads in a text file and parses it for specific strings.

Basically instead of opening the text file every time, I want to read the text file into memory and have it for the duration of the object.

I was wondering if there was a similar function to getline() I could use for a std::string like i can for a std::ifstream.

I realize I could just use a while/for loop but I am curious if there is some other way. Here is what I am currently doing:

file.txt: (\n represents a newline )

file.txt

My Code:

ifstream file("/tmp/file.txt");
int argIndex = 0;
std::string arg,line,substring,whatIneed1,whatIneed2;
if(file)
{
    while(std::getline(file,line))
    {
        if(line.find("3421",0) != string::npos)
        {
            std::getline(file,line);
            std::getline(file,line);
            std::stringstream ss1(line);
            std::getline(file,line);
            std::stringstream ss2(line);
            while( ss1 >> arg)
            {
                if( argIndex==0)
                {
                    whatIneed1 = arg;
                }
                argIndex++;
             }
             argIndex=0;
            while( ss2 >> arg)
            {
                if( argIndex==0)
                {
                    whatIneed2 = arg;
                }
                argIndex++;
             }
             argIndex=0;
         }
     }
 }

Where at the end whatIneed1=="whatIneed1" and whatIneed2=="whatIneed2".

Is there a way to do this with storing file.txt in a std::string instead of a std::ifstream asnd using a function like getline()? I like getline() because it makes getting the next line of the file that much easier.


Solution

  • If you've already read the data into a string, you can use std::stringstream to turn it into a file-like object compatible with getline.

    std::stringstream ss;
    ss.str(file_contents_str);
    std::string line;
    while (std::getline(ss, line))
        // ...