C++ 字符型 字符串型

1、字符型
作用:字符型变量用于显示单个字符。
语法:char ch=‘a’
注意:
1)、在显示字符型变量时,用单引号将字符括起来,不要用双引号;
2)、单引号内只能有一个字符,不可以使字符串;
3)、C和C++中字符型变量只占用1个字节;
4)、字符型变量并不是把字符本身放到内存中存储,而是将对应的ASCII编码放入到存储单元;

#include <iostream>
using namespace std;

int main()
{
    
    
    //1、字符型变量创建方式
    char ch = 'a';
    cout << ch << endl;
    //2、字符型变量所占内存大小
    cout << "char字符型变量所占内存:" << sizeof(char) << endl;
    //3、字符型变量常见错误
    //char ch2 = "b"; 创建字符型变量时候,要用单引号
    // char ch2='abcdef';创建字符型变量时候,单引号内只能有一个字符
    //4、字符型变量对应ASCII编码
    cout << (int)ch << endl;
    system("pause");
}

2、转义字符
作用:用于表示一些不能显示出来的ASCII字符。
现阶段我们常用的转义字符:\n,\,\t。

3、字符串型
作用:用于表示一串字符。
两种风格:
1)、char 变量名[] = “字符串值”
2)、C++风格字符串:string 变量名 = "字符串值"

#include <iostream>
#include<string>
using namespace std;

int main()
{
    
    
    //1、C风格字符串
    //注意事项:char 字符串名 []
    //注意事项:等号后面 要用双引号 包含起来字符串
    char str[] = "hello world";
    cout << str << endl;

    //2、C++风格
    string str2 = "hello world";
    cout << str2 << endl;
    system("pause");
    return 0;
}

4、布尔类型 bool
作用:布尔数据类型代表真或假的值
bool类型只有两个值:
1)、true – 真(本质是1);
2)、false–假(本质是0);
bool类型占1个字节大小。

#include <iostream>
using namespace std;

int main()
{
    
    
    //1、创建bool数据类型
    bool flag = true;
    cout << flag << endl;

    flag = false;
    cout << flag << endl;
    //2、查看bool类型所占内存空间
    cout << "bool类型所占内存空间:" << sizeof(bool) << endl;
}

5、数据的输入
作用:用于从键盘获取数据
关键字:cin
语法:cin>>变量

#include <iostream>
#include<string>
using namespace std;


int main()
{
    
    
    //1、整型
    int a = 0;
    cout << "请给整型变量a赋值:" << endl;
    cin >> a;
    cout << "整型变量a" << a << endl;
    
    //2、浮点型
    float f = 3.14f;
    cout << "请给浮点型变量f赋值:" << endl;
    cin >> f;
    cout << "浮点型变量ch=" << f << endl;

    //3、字符型
    char ch = 'a';
    cout << "请给字符型变量ch赋值:" << endl;
    cin >> ch;
    cout << "字符型变量ch=" << ch << endl;

    //4、字符串型
    string str = "hello";
    cout << "请给字符串 str赋值" << endl;
    cin >> str;
    cout << "字符串str=" << str << endl;

    //5、布尔类型
    bool flag = false;
    cout << "请给布尔类型flag赋值" << flag << endl;
    cin >> flag;
    cout << "布尔类型flag=" << flag << endl;

    system("pause");
}

Je suppose que tu aimes

Origine blog.csdn.net/weixin_42291376/article/details/120005327
conseillé
Classement