Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

c - Using the scanf function in while loop

I am attempting to format a space-delimited user input for a programming assignment.

Essentially, the input consists of an arbitrary number of expressions

L integer integer integer integer and C integer integer integer.

For example: L 1 1 5 7 C 4 5 3.

So far, I've managed to extract the integers depending on the initial character, and can iterate through the string using the scanf function:

char a;
while(scanf("%c", &a) == 1){
    if(a == 'C'){
        int inputX, inputY, inputR;
        scanf("%d %d %d", &inputX, &inputY, &inputR);
        printf("%d %d %d
", inputX, inputY, inputR);
    }
    else if(a == 'L'){
        int x1, y1, x2, y2;
        scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
        printf("%d %d %d %d
", x1, y1, x2, y2);
    }
}

Unfortunately, although this outputs the desired integers, the loop (and user input prompt) doesn't terminate.

Could someone please enlighten me as to why this is happening?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is because is always there to make scanf("%c", &a) == 1 always true.
Change your

while(scanf("%c", &a) == 1) 

to

while(scanf(" %c", &a) == 1)  
     //      ^space before format specifier.  

A space before %c will eat up this left behind by scanf (on pressing Enter).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...