没有运算符“>>”匹配这些操作数操作数类型是:std::istream >> double*

no operator ">>" matches these operands operand types are: std::istream >> double*

我正在尝试从结构中动态分配数组。我查看了 Whosebug 上的其他几个页面并尝试了一些代码,但 none 似乎适用于我的情况。我发现最接近我正在做的事情是在这里:

C++ dynamic memory allocation with arrays in a structure

出于某种原因,当我使用这行代码时:

cin >> testsPtr[i].students;

我得到标题中的错误。我也试过使用:

cin >> testsPtr[i]->students;

如何让用户为我的程序输入数据?

以下是编程挑战的规格:

修改编程挑战 1 的程序,允许用户输入 name-score 对。对于每个参加考试的学生,用户键入一个表示学生姓名的字符串,然后键入一个表示学生分数的整数。修改排序和 average-calculating 函数,使它们采用结构数组,每个结构包含单个学生的姓名和分数。在遍历数组时,使用指针而不是数组索引。

#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 行更改为此 cin >> *(testsPtr[i].students); 这是因为 testsPtr[i].students 是一个指针,所以您必须使用引用指针。确保正确初始化成员。

希望对您有所帮助。

读取值前取消引用指针:

cin >> *(testsPtr[i].students);

但在您必须创建对象 string 和指向它的引用指针之前:

testsPtr[i].students = new string;