I have two questions:
- why only when i do space in "%d " -->
scanf("%d ", &num);it works?
I tried fflush(stdin) \ _flushall() between the scnaf and the gets and it doesn't works, it skips the gets.
- When I do the space, it first does scanf then the gets and after that it print the number and print the string.
void main()
{
char ch, str[10];
int num;
printf("Enter your number : ");
scanf("%d ", &num);
printf("%d\n",num);
gets(str);
puts(str);
system("pause");
}
scanf("%d", &num);without a space after the"%d", stops scanning after reading a number. So with input 123Enter, the'\n'remains instdinfor the next input function like the now non-standardgets().gets()reads that single'\n'and returns. By adding a space,scanf("%d ", &num);consumes the white-space after the number and does not return until non-white-scape is entered after the number.By adding a space,
scanf("%d ", &num);does not return until non-white-space is entered after the number (as in'a'in the following). Sincestdinis usually line buffered, this means input of 2 lines needs to first occur. 123Enter abcEnter.Recommend to instead use
fgets()to read a line of user input.More robust code would check the results of
fgets(), sscanf()and usestrtol()rather thansscanf().