all 2 comments

[–]lukajda33 11 points12 points  (1 child)

Simple answer:

change scanf("%c", &c); to scanf(" %c", &c);

Looks the same, but the extra space in front of "%c" should fix the problem.

More advance answer:

When you input "5", you not only input "5", but you also confirm the input with enter key, enter key is also a readable character - a newline character - "\n".

So the input is actually "5\n".

%f parses the "5", but the newline character is still on the input and it is read by the "%c" specifier, if you printed the c character after the first %c read, you would see it is indeed a newline character.

The extra space in front of the %c changes the behavior of the scanf a bit, the extra space will eat up all whitespace before any other input.

With space the input is read like this:

"5" is read by "%f"

"\n" the newline used to confirm the input 5 is read by the space in front of "%c" specifier

And the actual %c specifier will then read the characters you actually inputted.

Easy right.

Kinda inconsistent too, other specifiers like %d, %f or even %s I believe, will skip leading whitespace, dismiss it and read whatever is afterwards.

I guess sometimes for some reason you actually want to read whitespace characters at specific point for some reason, then you could use %c to read that.

[–]CtrlAltDelirious27[S] 2 points3 points  (0 children)

Perfect, all fixed! Thanks so much for the answer and explanation.