Reputation: 51
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void) {
int input;
char ch;
scanf("%d%c", &input, &ch);
printf("%d %c", input, ch);
}
I just want ch has some character and input has trash value.
So i typed [q] and [enter].
But output is [trash value ?].
I don't know why ch has '?' not 'q'.
What happens in my buffer?
Upvotes: 0
Views: 91
Reputation: 51815
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;
}
Upvotes: 1
Reputation: 108968
scanf("%d%c", &input, &ch);
With input "q"
, scanf will try to interpret 'q'
as the first character of an integer (for the "%d"
conversion) and fail... scanf()
returns immediately with value 0
and without changing the value of ch
(the value of input
is indeterminate).
"q"
is still in the input buffer ready for the next input operayion.
Always check the return value of scanf()
int chk = scanf("%d%c", &value, &ch);
switch (chk) {
default: /* this didn't happen */;
/* let the compiler writers know about this */
break;
case EOF: /* error */;
/* value unchanged */
/* ch unchanged */
break;
case 0: /* no input found */;
/* value indeterminate */
/* ch unchanged */
break;
case 1: /* no input for ch found */;
/* value ok; (possibly) changed */
/* ch indeterminate */
break;
case 2: /* all ok */;
/* value ok; (possibly) changed */
/* ch ok; (possibly) changed */
break;
}
Upvotes: 4
Reputation: 1
#include <stdio.h>
int main(void) {
int input;
char ch;
scanf("%c%d", &input, &ch);
printf("%c %d",ch, input);
}
This code gives just the trash value as output nothing else.
Upvotes: 0