【发布时间】:2021-08-26 18:02:25
【问题描述】:
我目前正在学习 C++ 中的“结构”并坚持:
#include "iostream"
#define SIZE 100
struct date{
int day;
int month;
int year;
};
typedef struct{
char *name;
struct date date_of_birth;
int score;
} person;
void entry(person *roster){
person temp;
std::cout << "Input name: " << '\n';
gets(temp.name);
std::cout << "Date of birth: " << '\n';
std::cin >> temp.date_of_birth.day;
std::cin >> temp.date_of_birth.month;
std::cin >> temp.date_of_birth.year;
std::cout << "Score: " << '\n';
std::cin >> temp.score;
*roster = temp;
}
int main(int argc, char const *argv[]) {
person roster[SIZE];
// number of people in roster:
int n;
std::cin >> n;
for (int i = 0; i < n; i++){
entry(&roster[i]);
}
return 0;
}
在我输入 n 值后程序就结束了。请帮我解决这个问题,非常感谢
【问题讨论】:
-
除了奇怪的
#include "iostream"和std::cin,你的代码几乎是C。 -
如果你是从书本或教程中学习 C++,我建议你把它扔掉,给自己一个better C++ book。代码中有很多 C 主义和不良习惯,这是一本好的 C++ 书籍所没有的。
-
char *name;你从来没有分配内存来分配给它,相反你应该更喜欢 C++ 中的std::string -
请不要那样做。 C 和 C++ 是不同的语言。 非常不同。使用上面发布的链接查找 C++ 书籍。仅仅因为 C 代码碰巧在 C++ 中运行并不意味着您应该 编码。它只会给你带来巨大的痛苦
-
不要越过溪流,可能很糟糕,非常糟糕。如果您使用
std::cin,请不要使用gets。 (不要使用gets,因为它会溢出字符数组。)相反,使用std::string和std::getline,例如std::getline(std::cin, my_string);