深入理解 C++ 字符数据类型

字符数据类型是一种用于存储单个字符的数据类型。在代码中,它必须始终包含在单引号(‘ ‘)内。

#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++ 中的转义序列

转义序列是一些特殊的字符,它们决定了行应该如何在输出窗口上打印。转义序列总是以反斜杠 ‘\‘ 开头(也被称为转义字符)。下面提到了一些转义序列的示例:

序号

转义序列

字符 —

— 1. 换行符 2.

\\

反斜杠 3.

\t

水平制表符 4.

\v

垂直制表符 5.

\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++ 转义序列

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/33378.html
点赞
0.00 平均评分 (0% 分数) - 0