c++数据类型

来源:互联网 发布:知乎客户端 编辑:程序博客网 时间:2024/06/06 08:47

一、自定义数据类型——枚举类型

typedef可以将一个标识符声明成某个数据类型的别名,然后将这个标识符当做数据类型使用

#include <iostream>

using namespace std;

enum GameResult{WIN,LOSE,TIE,CANCEL};

int main(){

   GameResult result;//声明变量时,可以不写关键字enum

   enum GameResult omit=CANCEL;

   for(int count=WIN;count<=CANCEL;count++){//隐含类型转换

   result=GameResult(count);//显示类型转换

   if(result==omit)

       cout<<"The game was cancelled"<<endl;

   else{

       cout<<"The game was played ";

       if(result==WIN)

           cout<<"and we won!";

       if(result==LOSE)

           cout<<"and we lose.";

       cout<<endl;

   }

   }

    return 0;

}

注意:枚举元素按常量处理,不能对它们赋值。

枚举元素有默认值,依次为0、1、2等,可以在声明时另行定义枚举元素的值。

整数值不能直接赋给枚举变量,应进行强制类型转换

二、c++字符串

c++的基本数据类型变量中没有字符串变量,使用字符数组存储和处理字符串

由于对字符串的操作较为繁琐,所以c++对其进行了封装,形成了string类,使其更加方便的操作字符串

string类:

使用string类需要包含头文件string,string类封装了串的属性并提供了一系列允许访问这些属性的函数。

string 类提供了丰富的操作符,对操作符进行了重载

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

inline void test(const char *title,bool value){//根据value的值输出true或false,title为提示文字
    cout<<title<<" returns "<<(value?"true":"false")<<endl;
}

int main()
{
    string s1="DEF";
    cout<<"s1 is "<<s1<<endl;
    string s2;
    cout<<"Please enter s2: ";
    cin>>s2;
    cout<<"length of s2: "<<s2.length()<<endl;

    test("s1<=\"ABC\"",s1<="ABC");//比较运算符的测试
    test("\"DEF\"<=s1","DEF"<=s1);
    s2+=s1;//连接运算符的测试
    cout<<"s2=s2+s1: "<<s2<<endl;
    cout << "length of s2: "<<s2.length()<< endl;
    return 0;
}

运算结果:

s1 is DEF
Please enter s2: 123
length of s2: 3
s1<="ABC" returns false
"DEF"<=s1 returns true
s2=s2+s1: 123DEF
length of s2: 6

其中,例子中使用cin的>>操作符从键盘输入字符串,以这种方式输入时,空格会被作为输入的分隔符(空格后的不被读入)

使用头文件string中定义的getline(cin,string," 分隔符")可以从键盘读入字符串直到自定义的分隔符为止。无分隔符则默认换行符。



0 0