简体   繁体   English

从txt文件读入char数组的结构数组,需要帮助

[英]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. 我最近在uni上学习了C ++,我们必须制作一个电话簿程序,该程序可以使用txt文件作为联系人的输入/输出。 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. 我的问题是,重新启动程序后,(Ergo,将结构数组刷新到文件中并读回。)结构填充不正确。 The name char array is left empty, the address takes the name-value, and the phone number array tries to take the address. 名称char数组保留为空,地址使用名称值,电话号码数组尝试使用该地址。 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. 我必须将名字和姓氏存储在名称数组中,并用空格分隔,并将完整地址存储在其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();

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. 虽然我知道使用字符串会更好,并且更容易使用,但我想尽可能使用char数组来实现。

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. 读取数字并不会消除多余的换行符,因此您需要额外的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