Introduction

To avoid frustrating newline (\n) characters or other whitespace from previous inputs messing up a s_scanf of a char type, put a space in front of the %c in the format string.

Usage with scanf_s

Instead of the following code:

CHAR c;
scanf_s("%c", &c, 1); // Note no space in front of % in format string

Use the following:

CHAR c;
scanf_s(" %c", &c, 1); // Note the space in front of the % sign

I found this gem on Stack Overflow (the answer by Sourav Ghosh) here, and it works like a charm Note that I changed it to use the more secure scanf_s API.

Usage with Microsoft Generic Text Routines

Here is how to use with the Microsoft macros for regular/wide characters (beginning with _t) and using secure _tscanf_s:

TCHAR c;
_tscanf_s(TEXT(" %c"), &c, 1); // Note the space in front of the % sign

Check Return Value For Added Benefit

Microsoft describes the return values here:

Returns the number of fields successfully converted and assigned. The return value doesn’t include fields that were read but not assigned. A return value of 0 indicates no fields were assigned. The return value is EOF for an error, or if the end-of-file character or the end-of-string character is found in the first attempt to read a character. If format is a NULL pointer, the invalid parameter handler is invoked, as described in Parameter Validation. If execution is allowed to continue, scanf_s and wscanf_s return EOF and set errno to EINVAL.

TCHAR c;
if (_tscanf_s(TEXT(" %c"), &c, 1) == 1) {
  // Do something with c
}
else {
  // Deal with the error
}

Conclusion

I hope this has helped relieve some frustration - it is certainly not an immediately obvious fix one might think of when dealing with the quirky behavior one runs into. If you have any errata to report or constructive criticism, feel free to contact me using my contact form.

Thanks to Pexels for the free image