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.
Here are the steps:
Write a number :
and a newline,scanf("%s", buf)
has nothing to read from stdin, so input is requested,
f 10
and the enter keyscanf("%s", buf)
reads f
and stops at the space,strtol(buf, NULL, 10)
returns 0
, so the loop continuesWrite a number :
and a newline,scanf("%s", buf)
reads 10
and stops at the newline,strtol(buf, NULL, 10)
returns 10
, so the loop exits0
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.