C scanf requested format [duplicate]

2019-01-20 18:39发布

问题:

This question already has an answer here:

  • C: How can I make it so scanf() input has one of two formats? 2 answers

I need to scanf input in my C program. I did it like this:

scanf("{[ %lf; %lf],[ %lf; %lf],[ %lf; %lf]}", ...)

but it doesn't work for some expected inputs. It must work f.e. for

{[0;0],[10;10],[15;15]}

as well as for

{ [ 4 ; -1 ] , [ 7 ; 1.5 ] , [ 4 ; 4 ] }

or

But it needs to printf("Bad input.\n") if some { } ; , [ ] is missing or extra.

回答1:

Sounds like you just want to ignore whitespace, so add spaces to your format where it might occur:

scanf(" { [%lf ;%lf ] , [%lf ;%lf ] , [%lf ;%lf ] }", ...)

The only place you don't need it is immediately before %lf as that specifier automatically skips and ignores whitespace. Be sure to check the return value to ensure you matched 6 values. Unfortunately this will not tell you if the trailing ] or } is missing. For that you can add an extra %n specifier at the end and check to make sure it gets set:

int end = 0;
if (scanf(" { [%lf ;%lf ] , [%lf ;%lf ] , [%lf ;%lf ] }%n", ..., &end), end > 0) {
    // successful read
} else {
    // error
}