簡體   English   中英

在這種情況下如何從結構中輸入字符串數組?

[英]How to input string array from the structure in this case?

所以,我是初學者。 我有這段代碼和一些問題。 為了更好地理解,您將需要以下代碼:

struct student
{
    double marks;
    char name[50];
}stud[100],t;

int main()
{
    int i,j,n;
    cout<<"Enter the number of students: ";
    cin>>n;
    cout<<"Enter student info as name , marks\n";
    for(i=0;i<n;i++)
    {
        cin>>stud[i].name;
        cin>>stud[i].marks;
    }

問題是,而不是這部分:

struct student
{
    double marks;
    char name[50];
}stud[100],t;

應該有這部分:

struct student
{
    double marks[];
    string name[];
}stud[100],t;

但是后來我不知道如何將該數據輸入到程序中,因為那時 cin >> 不起作用。 任務說,當用戶輸入“”(ENTER)時,程序應該完成並按順序顯示學生打印。

你需要第二個循環。 我添加了常量——這是一種很好的做法,因此您的代碼中沒有“幻數”。 我添加了一個顯示 function 來演示它的工作原理!

#include <iostream>

using namespace std;

const int MAX_MARKS = 25;
const int MAX_STR = 50;
const int MAX_STUDENTS = 100;

struct student
{
    double marks[MAX_MARKS];
    char name[MAX_STR];
}stud[MAX_STUDENTS],t;

int main()
{
    int i,j,n;
    bool complete = false;
    cout<<"Enter the number of students: ";
    cin>>n;
    for(i=0; i < n && i < MAX_STUDENTS; ++i)
    {
        complete = false;
        cout<<"Enter student info as name , marks\n";
        cin>>stud[i].name;
        for (j = 0; j < MAX_MARKS; ++j)
        {
            if (!complete)
            {
                cout << "Enter mark #" << j+1 << ": ";
                if (!(cin >> stud[i].marks[j]))
                {
                    complete = true;
                    stud[i].marks[j] = -1.0;
                    cin.clear();
                    cin.ignore(100, '\n');
                }
            }
            else
                stud[i].marks[j] = -1.0; //0.0 is a valid grade so need a different value
        }
    }

    //Added a block for displaying the students
    for (i = 0; i < MAX_STUDENTS && i < n; ++i)
    {
        complete = false;
        cout << "Student #" << i+1 << ": " << stud[i].name << endl;
        for (j = 0; j < MAX_MARKS && !complete; ++j)
        {
            if (stud[i].marks[j] == -1.0)
                complete = true;
            else
                cout << "\tMark #" << j+1 << ": " << stud[i].marks[j] << endl;
        }
    }
}

標記和名稱數組是動態的,它們被稱為靈活數組成員,cpp 不支持它們你可以參考這個鏈接靈活數組成員在 C++ 中有效嗎? 此外,它們在 c 中得到支持,您最多可以有一個靈活的陣列成員,它應該在https://www.geeksforgeeks.org/flexible-array-members-structure-c/結尾

我相信這接近你想要的:

//10 marks by students
int m = 10;

struct student
{
    double marks[m];
    string name;
}stud[100],t;

int main()
{
    int i,j,n;
    cout<<"Enter the number of students: ";
    cin>>n;
    for(i=0;i<n;i++)
    {
        cout<<"Enter student info as name\n";
        cin>>stud[i].name;
        for(int j=0; j<m; ++j)
        {
            cout<<"Enter student marks "<<j+1<<endl; 
            cin>>stud[i].marks[j];
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM