【发布时间】:2021-12-04 04:26:05
【问题描述】:
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
string hometown;
int age;
int games;
int* hours = new int [games];
};
int main(){
int players;
Student* s = new Student [players];
cout << "How many esports players are there at TTU who major in csc?\n";
cin >> players;
cout << "\nPlease enter in information about each player: \n\n";
for(int i = 0; i < players; i++){
cout << "PLAYER " << (i + 1) << ":\n";
cout << "\tNAME:\t";
getline(cin >> ws, s[i].name);
cout << "\tHOMETOWN:\t";
getline(cin >> ws, s[i].hometown);
cout << "\tAGE:\t";
cin >> s[i].age;
cout << "\tHOW MANY GAMES DOES " << s[i].name << " PLAY?\t";
cin >> s[i].games;
for(int j = 0; j < s[i].games; j++){
cout << "NUMBER OF HOURS " << s[i].name << "PLAYED GAME" << (j + 1) << "\t";
cin >> s[i].hours[j];
}
}
return 0;
}
由于某种原因,for 循环在询问年龄后结束。我尝试了多个输入,它做同样的事情。我是 C++ 新手。有谁知道为什么?感谢您的宝贵时间
【问题讨论】:
-
开启编译器警告。考虑到它如何使用未初始化的成员变量默认分配
hours数组,您的结构在我看来非常粗略。在调试器中运行您的程序,以便在崩溃的代码行上获得一个断点(假设这是一个崩溃,这很可能)。您正在做一些奇怪的事情,还将基于行的输入与格式化的流输入混合在一起,但这可能不是现在的主要问题。 -
这里,let's look at the compiler warnings。打开和阅读编译器警告可能比寻求帮助要快得多。与
new Student [players]对应的players的值是多少? -
"for 循环在询问年龄后结束。" -- 更准确地说,程序 在询问年龄后结束(崩溃) .在你得出只有循环结束的结论之前,你应该测试这个假设。在循环之后放一些输出,可能是
cout << "Program done\n";,这样你就可以看到循环结束和程序结束之间的区别。 (在调试器中运行将是另一种查看差异的方法。) -
std::vector类在 C++ 中正式存在了将近 24 年。为什么还有人使用new[]?? -
@Swift-FridayPie -- 我认为 24 年的时间足以让我们看到向量是 C++ 的一部分。或者教学生
C,别再骗他们说他们正在学习 C++。