C++ 结构(struct) - 数据格式

如果,我需要一个变量来储存一个坐标,那么便需要两个int类型的变量来储存x,y,但是,在C++中有一个数据格式叫 struct 可以帮助你将x,y整合进一个结构中,然后使用成员运算符(.)来访问x,y。

栗子:

struct coordinate
    {
        int x;
        int y;
    };

这里,定义了一个叫coordinate的结构型变量,它有一个int类型的x成员和一个int类型的y成员,于是我们可以使用coordinate.x 访问x成员的值。

于是,看下面这个栗子:

#include 

using namespace std;

int main()
{
    struct coordinate
    {
        int x;
        int y;
    };
    coordinate coordinate_example;
    
    cout<<"x=";
    cin>>coordinate_example.x;
    cout<<"y=";
    cin>>coordinate_example.y;
    cout<

我们便可以输入x和y的值,储存在结构coordinate中且轻松访问成员x,y的值。

当然我们也可以使用 结构数组 。
来一个借书(Book Books)程序的栗子:

#include 
#include 

using namespace std;

int main()
{
    struct struct_book
    {
        string name;
        int bookNum;
        int time;
    };
    struct_book book[3];
    
    cout<<"Welcome to book books"<>book[i].name;
        cout<<" Book numbers:";
        cin>>book[i].bookNum;
        cout<<" Time(h):";
        cin>>book[i].time;
    }
    
    system("pause");
    return 0;
}

最后,在拓展一下,把我们的借书程序完善,可以一个人借任意本书(而不是上一个栗子中的常量3)。这个程序将用到 指针动态创建数组 的知识点

#include 
#include 

using namespace std;

int main()
{
    struct struct_book
    {
        string bookName;
        int time;
    };
    int num;
    string name;
    cout<<"Welcome to book books"<>name;
    cout<<"How many books do you want to book?"<>num;
    struct_book * book = new struct_book [num];
    for(int i=0;i!=num;i++)
    {
        cout<<"Book Num."<>book[i].bookName;
        cout<<" Time(day):";
        cin>>book[i].time;
    }
    
    system("pause");
    return 0;
}

输出:

Welcome to book books
 Name:Jake
How many books do you want to book?
3
Book Num.1
 Book's name(No space):PyQt4
 Time(day):10
Book Num.2
 Book's name(No space):Python2.xPrograming
 Time(day):5
Book Num.3
 Book's name(No space):Python-BeatifulSoup
 Time(day):3
请按任意键继续. . .

Now,enjoy your code!

你可能感兴趣的:(C++ 结构(struct) - 数据格式)