Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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\n", 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\n", 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?

like image 742
Julian Laval Avatar asked Nov 11 '13 17:11

Julian Laval


People also ask

Can you use scanf in a while loop?

scanf() function returns number of items it successfully reads. Since in your case it is reading one number n , scanf() returns 1. When you give a input file for the code to run, it returns 0 on reaching end of the file (EOF).

Why scanf is not working in loop in C?

That is because there is a left over newline character in the input buffer.

What is the syntax of scanf ()?

scanf("%d", &b); The program will read in an integer value that the user enters on the keyboard (%d is for integers, as is printf, so b must be declared as an int) and place that value into b. The scanf function uses the same placeholders as printf: int uses %d.

Can you use scanf in a function in C?

In C programming, scanf() is one of the commonly used function to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards.


1 Answers

This is because \n 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 \n left behind by scanf (on pressing Enter).

like image 197
haccks Avatar answered Oct 16 '22 15:10

haccks