kbirk
kbirk

Reputation: 4022

Efficiently reading tokens from individual lines of file

I'm parsing a text file, reading a line at a time. For each line, I need to check to see if the first n letters match a particular word, then process the line.

Currently it is done such as this:

while (!inFile.eof()) 
{
    std::string line;
    std::getline(inFile, line);            
    if (compareCaseInsensitive(line, "facet", 5)) 
    {               
        std::stringstream lineStream(line);   
        float a,b,c;
        std::string filler;
        lineStream >> filler >> filler >> a >> b >> c;  
    }
}

I'm reading the characters into a string, then copying those characters into a stringstream, then reading those characters out into the specific variables. This seems very inefficient. Is there anyway to read directly into the stringstream? or to extract the tokens from the string to prevent unnecessary copying?

Upvotes: 2

Views: 868

Answers (1)

Matt Phillips
Matt Phillips

Reputation: 9691

sscanf is probably what you're looking for:

char filler[64];
float a,b,c;
sscanf(line.c_str(), "%s %s %f %f %f", filler, filler, &a, &b, &c);

However you'll have to fix the format string to take care of whatever separator you actually use, I'm just guessing here (spaces) for the sake of concreteness. C format specifiers give you a lot (though not unbounded) leeway for accounting for uncertainty in exactly how the input string is formatted.

Upvotes: 2

Related Questions