C++结构体

一 一个结构体的例子

1 代码

#include <iostream>
using namespace std;
#include <stdlib.h>
#include <string.h>

struct movies_t {
    char title[50];
    int year;
}mine, yours;

void printmovie(movies_t movie);

int main() {
    char buffer[50];
    strcpy(mine.title, "2001 A Space Odyssey");
    mine.year = 1968;
    cout << "Enter title: ";
    cin.getline(yours.title, 50);
    cout << "Enter year: ";
    cin.getline(buffer, 50);
    yours.year = atoi(buffer);
    cout << "My favourite movie is:\n ";
    printmovie(mine);
    cout << "And yours:\n";
    printmovie(yours);
    return 0;
}

void printmovie(movies_t movie) {
    cout << movie.title;
    cout << " (" << movie.year << ")\n";
}

2 运行

[root@localhost test]# g++ test.cpp -g -o test
[root@localhost test]# ./test
Enter title: he boy
Enter year: 1999
My favourite movie is:
2001 A Space Odyssey (1968)
And yours:
he boy (1999)

二 结构体数组

1 代码

#include <iostream>
using namespace std;
#include <stdlib.h>
#include <string.h>

#define N_MOVIES 5

struct movies_t {
    char title[50];
    int year;
} films[N_MOVIES];

void printmovie(movies_t movie);

int main() {
    char buffer[50];
    int n;
    for (n = 0; n < N_MOVIES; n++) {
        cout << "Enter title: ";
        cin.getline(films[n].title, 50);
        cout << "Enter year: ";
        cin.getline(buffer, 50);
        films[n].year = atoi(buffer);
    }

    cout << "\nYou have entered these movies:\n";
    for (n = 0; n < N_MOVIES; n++)  
        printmovie(films[n]);
    return 0;
}

void printmovie(movies_t movie) {
    cout << movie.title;
    cout << " (" << movie.year << ")\n";
}

2 运行

[root@localhost test]# g++ test.cpp -g -o test
[root@localhost test]# ./test
Enter title: boy
Enter year: 1999
Enter title: girl
Enter year: 2000
Enter title: home
Enter year: 1987
Enter title: spring
Enter year: 1998
Enter title: cold
Enter year: 2012

You have entered these movies:
boy (1999)
girl (2000)
home (1987)
spring (1998)
cold (2012)

三 结构体指针

1 代码

#include <iostream>
using namespace std;
#include <stdlib.h>
struct movies_t {
    char title[50];
    int year;
};

int main() {
    char buffer[50];

    movies_t amovie;
    movies_t * pmovie;
    pmovie = & amovie;

    cout << "Enter title: ";
    cin.getline(pmovie->title, 50);
    cout << "Enter year: ";

    cin.getline(buffer, 50);
    pmovie->year = atoi(buffer);

    cout << "\nYou have entered:\n";
    cout << pmovie->title;
    cout << " (" << pmovie->year << ")\n";

    return 0;
}

2 运行

[root@localhost test]# g++ test.cpp -g -o test
[root@localhost test]# ./test
Enter title: boy
Enter year: 2010

You have entered:
boy (2010)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值