C++ char 类型:字符型和最小的整型

C++ 中没有 byte,Java 中有 byte。

但是 C++ 有 char,char 是可用来放整数的最小字节类型。

#include <iostream>

int main() {
    using namespace std;
    
    // 声明一个 char 类型的变量
    char ch;

    cout << "Enter a character: " << endl;
    cin >> ch;
    cout << "Hola! ";
    cout << "Thank you for the " << ch << " character." << endl;

    return 0;
}

char 打印出来的字符可能是 'M','s',但是在内存中,char 存放的确实字符对应的 ASCII 的整数值。

用单引号包裹的是字符,用双引号包裹的是字符串。

cout.put( )    // 可以用来显示单个字符

例子:

#include <iostream>

int main() {
    using namespace std;
    
    char ch = 'M';
    int i = ch;
    cout << "The ASCII code for " << ch << " is " << i << endl;

    cout << "And one to the character code: " << endl;

    ch = ch + 1;
    i = ch;

    cout << "The ASCII code for " << ch << " is " << i << endl;

    cout << "Display char ch using cout.put(ch): ";
    cout.put(ch);

    // 使用 cout.put() 输出字符常量
    cout.put('!');

    return 0;
}

char 看起来是个字符型,实际上是个整型,所以加减乘除都可以做。


为啥要有 cout.put( ) 呢?

猜你喜欢

转载自www.cnblogs.com/tuhooo/p/10719489.html