以下の実行結果1〜3 のように, 標準入力 (キーボード) から 1 文字入力すると, 入力した文字とその文字に対応する文字コードを表示するプログラムを作成したいです。.
ただし, 以下の条件を全て満たすこと.
- 文字の入力には, scanf または getchar 関数 を使用すること.
※ 標準入力を与えるには 実行後, 「文字入力>」の後にキーボードから文字を打ち込んで Enter キーを押す.
実行結果1
文字入力> T
T の 文字コードは 84 です
実行結果2
文字入力> D
D の 文字コードは 68 です
実行結果3
文字入力> U
U の 文字コードは 85 です
入力した文字を文字コードにする方法をお教えください。
文字コード変換
Re: 文字コード変換
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.
この記述からわかるように、scanf()の%cは「a character array」の先頭要素のポインタ、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.
すなわち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.
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)