繁体   English   中英

指向结构数组的指针仅显示 char 字段的第一个字符

[英]Pointer to structure array shows only the first character of a char field

我有以下代码:

#include <iostream>

using namespace std;

struct Materie {   //grades 
    float romana;
    float matematica;
    float fizica;

};

struct Elev {  // students structure, name, prename and grade obtained;
    char nume[30];
    char prenume[30];
    Materie nota;
};

void absolvent(Elev* elevi, int &n) { // fuction to remove studens with grade < 5
    for (int i = 0; i < n; i++) {
        if (elevi[i].nota.fizica < 5.0 || elevi[i].nota.matematica < 5.0 || elevi[i].nota.fizica < 5.0) {
            for (int j = i; j < n; j++) {
                *elevi[j].nume = *elevi[j + 1].nume;
                *elevi[j].prenume = *elevi[j + 1].nume;
                elevi[j].nota.romana = elevi[j + 1].nota.romana;
                elevi[j].nota.matematica = elevi[j + 1].nota.matematica;
                elevi[j].nota.fizica = elevi[j + 1].nota.fizica;
            }
            n--;
            i--;
        }
    }
}


int main() {
    int n;
    do {
        cout << "Introduceti numarul de elevi: ";
        cin >> n;
        if (n < 0 || n > 30) {
            cout << "0 < n < 30";
        } 
    } while (n < 0 || n > 30);
    Elev* elevi = new Elev[n];
    for (int i = 0; i < n; i++) {
        cout << "Introduceti numele elevului " << i + 1 << " : ";
        cin >> elevi[i].nume;
        cout << "Introduceti prenumele elevului " << i + 1 << " : ";
        cin >> elevi[i].prenume;
        cout << "Introduceti nota obtinuta la limba romana: ";
        cin >> elevi[i].nota.romana;
        cout << "Introduceti nota obtinuta la matematica: ";
        cin >> elevi[i].nota.matematica;
        cout << "Introduceti nota obtinuta la fizica: ";
        cin >> elevi[i].nota.fizica;
    }
    cout << elevi[0].nume << endl;
    cout << *elevi[0].nume << endl;

    return 0;
}

如果他获得的成绩之一小于 5,我想实现一个 function 从数组中删除 Elev(学生)。我想通过使用数组而不是向量来做到这一点。

在进行练习时,提出了以下问题:

1)。 为什么,在免除功能中,IDE 期望我将 * 传递给 elevi[i].nume (如果我只输入 elevi[i].nume:“表达式必须是可修改的左值”,则会出现错误),但是,对于elevi[i].nota.romana 是相反的(我在尝试放置elevi[i].nota.romana: "operand of ' " must pe a pointer" 时出错)?

2)。 为什么 elevi[0].nume 会返回“Alex”,例如,如果我在控制台中输入 Alex,但 *elevi[0].nume 只返回 A?

*elevi[j].nume只显示第一个字符的原因是它与elevi[j].nume[0]相同,更明显。

您不能分配给 arrays,但您可以分配给包含 arrays 的结构和类,并且解决方案比您想象的要简单得多。

for (int j = i; j < n-1; j++) {
    elevi[j] = elevi[j+1];
}

会做你想做的事。
(请注意,您需要降低循环的结尾,否则您将 go 超出有效索引。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM