c++ 如何读取txt文件并分配给结构类型数据?
答案:2 悬赏:40 手机版
解决时间 2021-02-08 13:14
- 提问者网友:骑士
- 2021-02-07 14:59
我目前的代码是这样的:
int main(){
Board itemList[100];
string fileName;
cout<<"Please enter the file name, include the.txt"< cin>>fileName;
ifstream ifs;
ifs.open(fileName.c_str());
if(ifs.fail()){
cout<<"failed to open"< }
else{
int cnt = 0;
while(ifs >> itemList[cnt].type){
ifs>>itemList[cnt].condition;
ifs>>itemList[cnt].price;
cnt++;
}
cnt = 0;
}
但是我的txt文件是用逗号隔开的:
chicken, for sale, 60
microwave, wanted, 201
bike, for sale, 60
bike, wanted, 50
microwave, for sale, 200
chicken, for sale, 25
chicken, wanted, 25
microwave, wanted, 10
microwave, for sale, 2
所以会变成这样temList[0].type = chicken
itemList[0].price = 0 itemList[0].condition = for
导致后面都不能用了
有没有好的解决办法? 谢谢!
最佳答案
- 五星知识达人网友:野味小生
- 2021-02-07 15:51
按行读取,然后按逗号将字符串分割保存到vector或者字符串数组中,然后再赋值给结构体的各部分
全部回答
- 1楼网友:拜訪者
- 2021-02-07 17:14
1. 需要用到fstream头文件
2. 用ifstream进行读取
3. 读取到结构体里面主要是每次读取对应结构体变量长度的数据到该结构体里面
具体参考下面demo
strcut stocktype
{
string personaddress;
string personcity;
string personstate;
int personzip;
};
void addresstype :: getdata()
{
ifstream infile;
int index;
string inputfile;
stocktype addresstypelist[no_of_person];
cout<<"enter the file path: ";
cin>>inputfile; //输入txt文件路径
cout<>addresstypelist[index].personaddress;
infile>>addresstypelist[index].personcity;
infile>>addresstypelist[index].personstate;
infile>>addresstypelist[index].personzip;
}
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯