我剛剛在我的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
您不檢查數組溢出。此外,如果您嘗試使用c樣式的字符串,請記住它們具有'\ 0'終止字符。 –
此外,請顯示您的文本文件的內容。 –
如何編寫文本文件?你如何在你的文本文件中終止你的字符串? –