[英]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.