c++ - 没有运算符 ">>"匹配这些操作数 操作数类型是:std::istream >> double*

标签 c++ pointers structure

我正在尝试从结构中动态分配数组。我查看了 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/

相关文章:

c - 尽管 0 长度缓冲区和编译器警告,scanf() 仍然可以工作。到底是怎么回事?

c - 我调用这个函数错了吗?

c++ - 有效处理 OOB,二维数组访问

c++ - decltype 的 const 限定符

c - 为什么数组指针打印不正确?

c - 使用 char 指针声明的字符串的内存地址

c# - 验证构造函数数据

android - com.myproject.api 和 com.myproject.api.impl 中的代码有什么指导方针吗?

c++ - 如何不调用位于链表节点中的对象的构造函数?

c++ - 将JNI代码移植到java并理解jdouble * 用法