C scanf requested format [duplicate]

2019-01-20 18:23发布

This question already has an answer here:

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

enter image description here

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

1条回答
淡お忘
2楼-- · 2019-01-20 19:13

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
}
查看更多
登录 后发表回答