Why do you wrote it in C++ when you have to use C? Or did you found the code in the net?
Anyway, your code is working and needs only a little tweaking to produce the expeceted result.
The
scanf()
function will stop when a not matching character occurs leaving all remaining characters in the input buffer. When reading an integer value that means that the line feed character
\n
placed in the buffer by pressing the return key stops the conversion but is left in the buffer. When then calling
scanf()
again within the loop, it reads that line feed which is treated as unknown character.
The solution is quite simple: Tell
scanf()
to read and ignore the line feed:
scanf_s("%d\n", &n);
To get the required output format, all you have to do is replacing the
\n
in the
printf()
format string by a space, add a space at the end when printing "Unknown Character", and finally print a new line before terminating the application.