字符数据类型是一种用于存储单个字符的数据类型。在代码中,它必须始终包含在单引号(‘ ‘)内。
#include
using namespace std;
int main()
{
char c = ‘g‘;
cout << c;
return 0;
}
输出
g
ASCII 值
ASCII 值代表美国信息交换标准代码。它用于表示所有字符对应的数值。
- ‘a‘ 到 ‘z‘ 的 ASCII 范围 = 97-122
- ‘A‘ 到 ‘Z‘ 的 ASCII 范围 = 65-90
- ‘0‘ 到 ‘9‘ 的 ASCII 范围 = 48-57
将字符值转换为对应的 ASCII 值
要将字符转换为 ASCII 值,我们需要使用 int(字符) 对其进行类型转换,以获取对应的数值。
#include
using namespace std;
int main()
{
char c = ‘g‘;
cout << "The Corresponding ASCII value of 'g' : ";
cout << int(c) << endl;
c = 'A';
cout << "The Corresponding ASCII value of 'A' : ";
cout << int(c) << endl;
return 0;
}
输出
The Corresponding ASCII value of ‘g‘ : 103
The Corresponding ASCII value of ‘A‘ : 65
将 ASCII 值转换为对应的字符值
如果我们要将 ASCII 值转换回对应的字符值,则需要使用 char(整数) 进行类型转换,以获取对应的字符。
#include
using namespace std;
int main()
{
int x = 53;
cout << "The Corresponding character value of x is : ";
cout << char(x) << endl;
x = 65;
cout << "The Corresponding character value of x is : ";
cout << char(x) << endl;
x = 97;
cout << "The Corresponding character value of x is : ";
cout << char(x) << endl;
return 0;
}
输出
The Corresponding character value of x is : 5
The Corresponding character value of x is : A
The Corresponding character value of x is : a
C++ 中的转义序列
转义序列是一些特殊的字符,它们决定了行应该如何在输出窗口上打印。转义序列总是以反斜杠 ‘\‘ 开头(也被称为转义字符)。下面提到了一些转义序列的示例:
转义序列
—
\\
\t
\v
\0
#include
using namespace std;
int main()
{
char a = ‘G‘;
// 水平制表符
char b = ‘\t‘;
char c = ‘F‘;
char d = ‘\t‘;
char e = ‘G‘;
// 换行符
char f = ‘
‘;
string s = "is the best";
cout << a << b << c << d << e << f << s;
return 0;
}
输出
G F G
is the best
要了解更多相关信息,请参阅文章 – C++ 转义序列