簡體   English   中英

從txt文件讀入char數組的結構數組,需要幫助

[英]Read in from txt file into an array of structs of char arrays, help needed

我最近在uni上學習了C ++,我們必須制作一個電話簿程序,該程序可以使用txt文件作為聯系人的輸入/輸出。 我的問題是,重新啟動程序后,(Ergo,將結構數組刷新到文件中並讀回。)結構填充不正確。 名稱char數組保留為空,地址使用名稱值,電話號碼數組嘗試使用該地址。 我必須將名字和姓氏存儲在名稱數組中,並用空格分隔,並將完整地址存儲在其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];

雖然我知道使用字符串會更好,並且更容易使用,但我想盡可能使用char數組來實現。

編輯:文本文件當前只是一個測試/占位符:

1
Todor Penchev
Sevlievo, BG
0854342387

讀取數字並不會消除多余的換行符,因此您需要額外的getline來消除它們。

    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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM