Question

So I've got some code that splits a string into some other variables with sscanf that looks like this.

if(sscanf(input_line.c_str(), "%s %s %lf %lf %lf", &string1, &string2, &point1, &point2, &point3) != 5) {
    //does stuff
    throw;
}

I use the return value of sscanf to validate the input string.

I would use

istringstream ss(input_line);
ss >> string1 >> string2 >> point1 >> point2 >> point3;
if( ??????? ){
    //does stuff
    throw;
}

But I don't know how to verify if there were exactly 5 things populated. I'd love to get rid of the legacy C code as I loath char arrays but I don't want to lose the error checking. I'd very much appreciate any advice to adapt this istringstream code or use entirely different c++ style code to get rid of the char arrays but keep the existing functionality.

Thanks in advance,

Max

Était-ce utile?

La solution

First of all remember that all input operator functions (>>) returns the input stream, and secondly remember that a stream can be used as a boolean condition.

This means you can do e.g.

std::string string1, string2;
double point1, point2, point3;

if (some_input_stream >> string1 >> string2 >> point1 >> point2 >> point3)
{
    // All is okay
}
else
{
    // One of the input operations failed
}

To know exactly which input operation failed, you can do them one at a time.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top