2015-02-05 111 views
0

這是結構結構數組打印不正確| 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] != '\0') 
    { 
     StudentList2[count5].firstName[countfName] = 
      StudentList1[count5].firstName[countfName]; 
     countfName++; 
    } 

    while(StudentList1[count5].lastName[countlName] != '\0') 
    { 
     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++; 
    } 

現在的角色,當我嘗試這樣做,這樣我只是得到一個一堆垃圾,我得到的第一個名字打印,但之後,一堆垃圾和姓氏太多,但只是垃圾之間。

+1

這聽起來像你的字符串不是null終止。例如'[B] [o] [b] [0]' – 2015-02-05 19:47:56

+0

是否有另一個哨兵我可以選擇不是null? – user3387140 2015-02-05 19:49:25

+0

StudentList2中的名字和姓氏最後需要'\ 0'。在每個while循環出來之後這樣做。 – Kamehameha 2015-02-05 19:49:40

回答

0

你結束在複製時忘記終止零點。

由於結構是可複製,你可以做這樣的:

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

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

這是略少出錯。

+0

哇,我不能相信我忘記了,非常感謝你! – user3387140 2015-02-05 19:58:05

0

在您的代碼:

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

你有當它擊中它停止「\ 0」,但你永遠不重新編寫「\ 0」到StudentList2

0

首先,你需要複製終止零:

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

,那麼你需要重新設置計數器:在你最while環路​​前

countfName = countlName = 0; 

你應該這樣做