This is an excellent example of why you should always check the return value of scanf
(and related functions).
The format string you give to scanf
("%d%c"
) expects, as input, a valid decimal number followed (immediately) by a character. If you input q
by itself, the function will fail to read a decimal value and stop at that point – returning 0
, because none of the arguments was successfully assigned a value. In that case, neither input
or ch
will have predictable values, as you have not initialized either.
Also note that, if you type in just a number (i.e. 12
), the terminating newline (from the Enter key) will be assigned to ch
.
Here's your code with an input-check added and default values assigned to your two variables:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main(void)
{
int input = 42;
char ch = '$';
if (scanf("%d%c", &input, &ch) != 2) {
printf("Error: Please input a number and a character!\n");
}
printf("%d %c", input, ch);
return 0;
}
Alternatively, if (as I think you suggest in your question), you want to still read the ch
value but leave input
as its original ('trash') value, you can re-read the input if/when the first call to scanf
fails. On that second call, remove the %d
format specifier:
int main(void)
{
int input = -137; // Let's use this as a 'trash' value.
char ch = '$';
if (scanf("%d%c", &input, &ch) != 2) {
if (scanf("%c", &ch) != 1) printf("Error: Failed to read anything!");
}
printf("%d %c", input, ch);
return 0;
}