Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using scanf in for loop

Tags:

c

Here is my c code:

int main()
{
    int a;
    for (int i = 0; i < 3; i++)
        scanf("%d ", &a);

    return 0;
}

When I input things like 1 2 3, it will ask me to input more, and I need to input something not ' '.

However, when I change it to (or other thing not ' ')

scanf("%d !", &a);

and input 1 ! 2! 3!, it will not ask more input.

like image 224
Rikka Avatar asked Dec 06 '15 13:12

Rikka


1 Answers

The final space in scanf("%d ", &a); instructs scanf to consume all white space following the number. It will keep reading from stdin until you type something that is not white space. Simplify the format this way:

scanf("%d", &a);

scanf will still ignore white space before the numbers.

Conversely, the format "%d !" consumes any white space following the number and a single !. It stops scanning when it gets this character, or another non space character which it leaves in the input stream. You cannot tell from the return value whether it matched the ! or not.

scanf is very clunky, it is very difficult to use it correctly. It is often better to read a line of input with fgets() and parse that with sscanf() or even simpler functions such as strtol(), strspn() or strcspn().

like image 123
chqrlie Avatar answered Oct 28 '22 10:10

chqrlie