一 一个结构体的例子
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)