【发布时间】:2017-12-08 03:04:18
【问题描述】:
我正在尝试从结构中动态分配数组。我在stackoverflow上查看了其他几个页面并尝试了一些代码,但似乎没有一个适合我的情况。我发现最接近我正在做的事情是在这里:
C++ dynamic memory allocation with arrays in a structure
由于某种原因,当我使用这行代码时:
cin >> testsPtr[i].students;
我收到标题中的错误。我也试过使用:
cin >> testsPtr[i]->students;
如何让用户为我的程序输入数据?
以下是编程挑战的规格:
修改编程挑战 1 的程序以允许用户输入名称-分数对。对于每个参加考试的学生,用户键入一个代表学生姓名的字符串,后跟一个代表学生分数的整数。修改排序和平均计算函数,使其采用结构数组,每个结构包含单个学生的姓名和分数。在遍历数组时,使用指针而不是数组索引。
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
void averageScore(double*, int);
void sort(double*, int);
int numScores;
struct studentScores {
double *scores;
string *students;
};
cout << "How many test scores will you be entering?" << endl;
cin >> numScores;
studentScores *testsPtr = new studentScores[numScores];
for (int i = 0; i < numScores; i++) {
cout << "What is the #" << i + 1 << " students name?" << endl;
cin >> testsPtr[i].students;
for (int j = 0; j < numScores; j++) {
cout << "Please enter test score #" << j + 1 << endl;
do {
cin >> testsPtr[j].scores;
if (testsPtr[i].scores < 0) {
cout << "A test score can't be less than 0. Re-enter test score #" << i + 1 << endl;
}
} while (testsPtr[i].scores < 0);
}
}
cout << endl;
/*sort(testsPtr.scores, numScores);
cout << endl;
averageScore(testScores, numScores);
cout << endl;*/
for (int i = 0; i <= numScores; i++) {
cout << testsPtr->students << " test scores are: " << endl;
for (int j = 0; j <= numScores; j++) {
cout << testsPtr->scores;
}
}
delete[] testsPtr;
testsPtr = nullptr;
return 0;
}
【问题讨论】:
-
你必须为 *scores 和 *students 分配内存。而且你不能简单地写 cin >> testsPtr[i].students 因为这意味着读取指针的值而不是数组值
-
或者不让它们成为指针?
-
为什么不使用
std::vector<std::string> students;?还有std::vector<double> scores?还有std::vector<studentScores> testPtr(numScores)? -
这是来自 c++ early objects 一书的编程挑战。我想使用结构和指针来修改旧程序。
-
这是来自 c++ early objects 一书的编程挑战。 -- 问题是几乎没有人,如果有人读过这本书来确切地知道什么可以或不能使用。 cmets 假设您希望在编写 C++ 代码时使用最佳或更好的实践。