簡體   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