tags:

views:

147

answers:

3

And please don't say it's fscanf() ;P

I'm trying to replace this line:

if ( fscanf(fp, "P%c\n", &ch) != 1 )

If I understand correctly, it tries to read in a char and store it to &ch, only if it's between a 'P' and a '\n'. Is that right? And if it succeeds, it returns 1 (the number of characters it read)?

I'm trying to come up with a C++ version. Is there any easy way to do a formatted read like that? Or do I need to use fstream, operator>>, and nested if statements?

+4  A: 

Safe C++ alternative with type checks is std::stringstream.

Kirill V. Lyadvinsky
Yeah, I've looked at this a bit, but I can't seem to find a way to format the input like fscanf did ("P%c\n"). Am I stuck doing it the tedious way?
Andre
I think that you can use stringstream to read the whole line as a string. Then you can get you char at the proper position in you string.
Alceu Costa
A: 

In Visual Studio, the safe, but non-portable, equivalent function is fscanf_s.

In general, for portability, you would use one of the stream classes, which, as you note, can be a pain to format correctly.

jwismar
A: 

There's no need for nested if statements, you can use just one like you have there in fscanf.

//... open it and such
{
    // Leave ch to fall off, if it's not within the range.
    char ch;
    file >> ch;
    if ('P' <= ch && 'n' >= ch) {
       // Success!
    }
}

Also, while I despise fscanf and friends, there ARE use cases for them, the format string can be surprisingly expressive. In addition, you should use fscanf_s, which I believe has extra parameters for safety. Any compiler that warns about fscanf should suggest alternatives in the warning.

DeadMG
Er... I don't think what you've coded is the equivalent of that fscanf call, but yeah, I'll have to use fstream.
Andre
@Andre: It's true, I never really learned to use fscanf. Just guesstimated off your original description.
DeadMG