结构数组打印不正确 | C++

Structure Array not printing correctly | C++

这是结构

struct Student{
    char firstName[MAX_LEN + 1];
    char lastName[MAX_LEN + 1];
    float gpa;
};

所以让我说 StudentList1 有正确的数据。

count Struct1 是输入了多少个名字。

Student StudentList1[10];

int count5 = 0, countfName = 0, countlName = 0;

while(count5 < countStruct1)
{
    while(StudentList1[count5].firstName[countfName] != '[=11=]')
    {
        StudentList2[count5].firstName[countfName] = 
            StudentList1[count5].firstName[countfName];
        countfName++;
    }

    while(StudentList1[count5].lastName[countlName] != '[=11=]')
    {
        StudentList2[count5].lastName[countlName] =
            StudentList1[count5].lastName[countlName];
        countlName++;
    }
        StudentList2[count5].gpa = StudentList1[count5].gpa;
        count5++;
}

现在出于某种原因,当我尝试此代码时,没有使用姓氏和名字字符的数组

while(count6 < count5)
    {
        cout << "Name: " << StudentList2[count6].firstName << " " << StudentList2[count6].lastName << "\n";
        count6++;
    }

现在,当我尝试这样做时,我得到了一堆垃圾,我得到了名字,但之后是一大堆垃圾和姓氏,但中间只有垃圾。

在您的代码中:

while(StudentList1[count5].firstName[countfName] != '[=10=]')
{
    StudentList2[count5].firstName[countfName] = 
        StudentList1[count5].firstName[countfName];
    countfName++;
}

你让它在遇到 '\0' 时停止,但你永远不会将 '\0' 重写到 StudentList2

的末尾

您在复制时忘记了终止零。

由于结构是可复制的,您可以这样做:

while (count5 < countStruct1)
{
    StudentList2[count5] = StudentList1[count5];
    count5++;
}

for (int i = 0; i < countStruct1; i++)
{
    StudentList2[i] = StudentList1[i];
}

更不容易出错。

首先,您需要复制终止零:

StudentList2[count5].firstName[countfName] = '[=10=]';
StudentList2[count5].lastName[countlName] = '[=10=]';

那么您需要重置计数器:

countfName = countlName = 0;

您应该在最外层 while 循环 count5++ 之前执行此操作