Character
ใน C++ จะมี character type ดังต่อไปนี้
- char: เป็น default type โดยปกติแล้วจะมี 8 bit (ISO-646, ASCII) มีทั้งหมด 256 ตัวอักษร
- signed char/ unsigned char: เหมือนกับ char แต่จะมีผลตอนนำมาคำนวณ บวก ลบ คูณ หาร หรืออื่นๆ
- wchar_t: จะเป็น char sets ที่มากกว่าเช่น Unicode
- char16_t: คือ 16 bit char set เช่น UTF-16
- char32_t: คือ 32 bit char set เช่น UTF-32
ตัวอย่างค่าของ char
void intval()
{
for (char c; cin >> c;)
cout << "the value of " << c << " is " << int{ c } << "\n";
}
int main()
{
intval();
}
แสดงผล
a
the value of a is 97
b
the value of b is 98
A
the value of A is 65
B
the value of B is 66
*
the value of * is 42
#
the value of # is 35
@
the value of @ is 64
ตัวอย่างการแปลงค่า int เป็น char
void chardigit()
{
for (int i = 0; i <= 60; ++i)
cout << static_cast('0' + i);
cout << "\n";
}
int main()
{
chardigit();
}
แสดงผล
0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijkl
เราสามารถพิมพ์ char โดยใช้ตัวเลข Decimal, Octal (\ back slash ตามด้วยตัวเลข) หรือ Hexadecimal (\x back slash x ตามด้วยตัวเลข) ดังตัวอย่าง
void printChar(char a)
{
cout << "Character is: " << a << "\n";
}
int main()
{
printChar('\x30'); //Hexadecimal
printChar('\60'); //Octal
}
แสดงผล
Character is: 0 //Hexadecimal '0'
Character is: 0 //Octal '0'
อักขระพิเศษ
| Name | ASCII Name | C++ Name |
| Newline | NL(LF) | \n |
| Horizontal tab | HT | \t |
| Vertical tab | VT | \v |
| Backspace | BS | \b |
| Carriage return | CR | \r |
| Form feed | FF | \f |
| Alert | BEL | \a |
| Backslash | \ | \\ |
| Question mark | ? | \? |
| Single quote | ' | \' |
| Double quote | " | \" |
| Octal number | 000 | \000 (0 คือตัวเลข) |
| Hexadecimal number | hhh | \xhhh...(h คือตัวเลข) |
