Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

c - Convert scanf to a different argument size

Let's say I have the following to print a character entered by the user (using int to allow EOF in other places):

int ch;
scanf("%d", &ch);
printf("The character you entered was: %c
", (char) ch);

Here, I am converting to a char in the printf function. How would I do that in the scanf function instead? For example, something like:

int ch;
scanf("%c", & (char) ch); // ???
printf("The character you entered was: %c
", ch);

How would that be done?

question from:https://stackoverflow.com/questions/65910466/convert-scanf-to-a-different-argument-size

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...