You would scan a char
and afterward convert it to int
:
char c;
int ch;
if (scanf(" %c", &c) == 1) {
ch = (unsigned char) c;
} else {
ch = EOF;
}
The explicit conversion to unsigned char
produces a result analogous to getchar()
's. There is a subsequent automatic conversion from that result to type int
. In the case where scanf()
fails to scan a character (other than leading whitespace), ch
is set explicitly to EOF
, much as getchar()
would do.
Note also that the given format explicitly skips leading whitespace, as %d
and most other format directives automatically do, but %c
does not. This is for consistency with your %d
variation -- it is not what getchar()
does.
If you scan just one char
into an otherwise uninitialized int
, then you may not use the resulting int
value without evoking undefined behavior on account of the three indeterminate bytes. Even if you initialized your int
first -- to zero, say -- scanning one byte into it does not necessarily produce an int
with the same value as that char
, so no, no trick with scanning directly to the int
is reliable. Theoretical UB aside, that could not be expected to work as you want on a big-endian machine or if the integer value of the scanned character were negative.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…