box さんが書きました: ↑3年前
よかったら使ってください。
ソースコードはちゃんと字下げしましょうね。
コード:
#include <stdio.h>
int main(void)
{
int c;
printf("文字入力> ");
scanf("%c", &c);
printf("%c の文字コードは %d です。\n", c, c);
return 0;
}
char*型のデータを要求するscanf()の書式%cに対し、int*型のデータを渡しているため、未定義動作になります。
また、提示された実行結果と比べ、「の」と「文字」の間のスペースが抜け、余計な「。」が入っています。
N1570 7.21.6.2 The fscanf function より引用:
10
(中略) If this object
does not have an appropriate type, or if the result of the conversion cannot be represented
in the object, the behavior is undefined.
c
Matches a sequence of characters of exactly the number specified by the field
width (1 if no field width is present in the directive).286)
If no l length modifier is present, the corresponding argument shall be a
pointer to the initial element of a character array large enough to accept the
sequence. No null character is added.
この記述からわかるように、scanf()の%cは「a character array」の先頭要素のポインタ、
すなわちchar*型のデータを要求します。
上の引用はfscanf()についてですが、scanf()についても同じはずです。
N1570 7.21.6.4 The scanf function より引用:
2
The scanf function is equivalent to fscanf with the argument stdin interposed
before the arguments to scanf.