cwhile-loopscanfstrtol

C double printf() when a space is put in my scanf()


I've been trying to make this code work properly:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const **argv) {
    char buf[100];
    int var = 0;
    do {
        printf("Write a number :\n");
        scanf("%s", buf);
    } while ((int)strtol(buf, NULL, 10) == 0);

    return 0;
}

In the console it goes like that :

chaouchi@chaouchi:~/workspace/Demineur$ ./a.out
Write a number :
f 10
Write a number :
chaouchi@chaouchi:~/workspace/Demineur$

I don't understand why the program stop and ignore my scanf() during the second iteration of the while loop.


Solution

  • Here are the steps:

    This is what you observe: if you provide more than one word, multiple scanf() calls read them before more input is requested from the terminal.