Structure Array打印不正确|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] != '')
    {
        StudentList2[count5].firstName[countfName] = 
            StudentList1[count5].firstName[countfName];
        countfName++;
    }
    while(StudentList1[count5].lastName[countlName] != '')
    {
        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 (count5 < countStruct1)
{
    StudentList2[count5] = StudentList1[count5];
    count5++;
}

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

其稍微不易出错。

在您的代码中:

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

当它到达"\0"时,您可以停止它,但您永远不会将"\0"重新写入StudentList2 的末尾

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

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

然后你需要重置你的计数器:

countfName = countlName = 0;

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

最新更新