简体   繁体   中英

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

I've just recently taken C++ in my uni, and we have to make a phonebook program, which works with a txt file as input/output for the contacts. My problem is, that after restarting the program, (Ergo, flush the array of structures into the file and read it back in.) the structures are filled incorrectly. The name char array is left empty, the address takes the name-value, and the phone number array tries to take the address. I have to store first and last names in the name array, separated by a white space, as well as the full address into it's char array.

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

Structure defined as:

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

derp b[100];

While I know using strings is better, and a whole lot easier, I'd like to do it with char arrays if possible.

EDIT: Text file is currently just a test/placeholder:

1
Todor Penchev
Sevlievo, BG
0854342387

reading a number does not get rid of the extra newline, so you need extra getlines to get rid of them.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM