Search code examples
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:

    • the first iteration prints Write a number : and a newline,
    • scanf("%s", buf) has nothing to read from stdin, so input is requested,
      • you type f 10 and the enter key
      • scanf("%s", buf) reads f and stops at the space,
    • strtol(buf, NULL, 10) returns 0, so the loop continues
    • the second iteration prints Write a number : and a newline,
    • scanf("%s", buf) reads 10 and stops at the newline,
    • strtol(buf, NULL, 10) returns 10, so the loop exits
    • the program finishes with a 0 status (success).

    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.