我正在尝试从结构中动态分配数组。我查看了 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;
}
最佳答案
在读取值之前取消引用指针:
cin >> *(testsPtr[i].students);
但在您必须创建对象 string
和指向它的引用指针之前:
testsPtr[i].students = new string;
关于c++ - 没有运算符 ">>"匹配这些操作数 操作数类型是:std::istream >> double*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47707086/