Final space in scanf("%d ", &a); instructs scanf consume all spaces after the number. It will read with stdin until you type something that is not white. Simplify the format as follows:
scanf("%d", &a);
scanf will still ignore the space before the numbers.
And vice versa, the format is "%d !" consumes any space after number and one ! . It stops scanning when it receives this character, or another space character that it leaves in the input stream. You cannot indicate from the return value whether it matches ! or not.
scanf very awkward, it is very difficult to use correctly. It is often better to read the input line with fgets() and parse it with sscanf() or even simpler functions like strtol() , strspn() or strcspn() .
source share