- 文字列は文字コードの羅列で表す
- 文字列の終わりには0をつける
- 文字列はchar型の配列変数に入れる
- 文字列は配列変数の名前で扱う
文字を受け取って、その文字のコードを表示するC++プログラム:
#include <iostream>
using namespace std;
void ShowCode(char ch) {
cout << (int)(unsigned char)ch << endl;
}
int main() {
cout << "type char > " << flush;
char ch;
cin >> ch;
ShowCode(ch);
}
ちなみに、PHPで同じことをやりたい場合はord()を使う。
以下のプログラムを実行すると、”Hello!”という文字列の各文字のコードが表示され、最後に0が表示される。
#include <iostream>
using namespace std;
int main() {
char hello[] = "Hello!";
for (int i = 0; i < (int)sizeof hello; ++i) {
cout << (int)(unsigned char)hello[i] << ", ";
}
cout << endl;
}