2013-12-10 43 views
0

我剛剛在我的uni中使用了C++,並且我們必須製作一個電話簿程序,該程序使用txt文件作爲輸入/輸出聯繫人。 我的問題是,重新啓動程序後(Ergo,將結構數組刷入文件並讀回。)結構填充不正確。名稱char數組保留爲空,地址採用名稱值,電話號碼數組嘗試獲取地址。我必須在名稱數組中存儲名字和姓氏,用空格分隔,並將完整的地址存儲到它的字符數組中。從txt文件讀入char數組的結構數組,需要幫助

ifstream ifile; 
ifile.open("phonebook.txt"); 

while(ifile.peek()!=EOF) 
{ 
    string temp; 
    ifile>>b[a].id; 
    getline(ifile, temp); 
    for(int i = 0;i < temp.length();i++) 
     b[a].name[i] = temp[i]; 
    temp.clear(); 
    getline(ifile, temp); 
    for(int g = 0;g < temp.length();g++) 
     b[a].address[g] = temp[g]; 
    temp.clear(); 
    ifile>>b[a].number; 
    a++; 
} 

ifile.close(); 

結構定義爲:

struct derp 
{ 
    int id; 
    char name[25]; 
    char address[25]; 
    char number[10]; 
}; 

derp b[100]; 

雖然我知道使用字符串比較好,而且容易許多,我想和字符數組如果可能的話去做。

編輯: 文本文件目前只是測試/佔位符:

1 
Todor Penchev 
Sevlievo, BG 
0854342387 
+0

您不檢查數組溢出。此外,如果您嘗試使用c樣式的字符串,請記住它們具有'\ 0'終止字符。 –

+0

此外,請顯示您的文本文件的內容。 –

+0

如何編寫文本文件?你如何在你的文本文件中終止你的字符串? –

回答

0

閱讀數不擺脫額外的換行符,所以你需要額外的getlines擺脫他們的。

fstream ifile; 
    ifile.open("phonebook.txt"); 
    a = 0; 
    while(ifile.peek()!=EOF) 
    { 
     string temp; 
     ifile>>b[a].id; 
     cout << "Id=:" << b[a].id << endl; 
     getline(ifile, temp); // Read end of line 
     getline(ifile, temp); 
     cout << "name=:" << temp << endl; 
     for(int i = 0;i < temp.length();i++) 
      b[a].name[i] = temp[i]; 
     temp.clear(); 
     getline(ifile, temp); 
     cout << "address=:" << temp << endl; 
     for(int g = 0;g < temp.length();g++) 
      b[a].address[g] = temp[g]; 
     temp.clear(); 
     ifile>>b[a].number; 
     getline(ifile, temp); // Read end of line 
     cout << "number=:" << b[a].number << endl; 
     cout << b[a].id << endl << b[a].name << endl << b[a].address << endl << b[a].number << endl; 
     a++; 
    } 

    ifile.close(); 
+0

好吧,現在我覺得很愚蠢。這很明顯,現在我知道了。 –

+0

您可以用strncpy(dst,src,len)一次替換一個字節的循環。比for循環更清晰。 –