c++ 如何读取txt文件并分配给结构类型数据?
我目前的代码是这样的:intmain(){BoarditemList[100];stringfileName;cout<<"Pleaseenterthefilename,...
我目前的代码是这样的:
int main(){
Board itemList[100];
string fileName;
cout<<"Please enter the file name, include the.txt"<<endl;
cin>>fileName;
ifstream ifs;
ifs.open(fileName.c_str());
if(ifs.fail()){
cout<<"failed to open"<<endl;
}
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
导致后面都不能用了
有没有好的解决办法? 谢谢! 展开
int main(){
Board itemList[100];
string fileName;
cout<<"Please enter the file name, include the.txt"<<endl;
cin>>fileName;
ifstream ifs;
ifs.open(fileName.c_str());
if(ifs.fail()){
cout<<"failed to open"<<endl;
}
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
导致后面都不能用了
有没有好的解决办法? 谢谢! 展开
1个回答
展开全部
按行读取,然后按逗号将字符串分割保存到vector或者字符串数组中,然后再赋值给结构体的各部分
追问
能给个样例吗,谢谢
追答
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
typedef struct
{
string type;
string condition;
double price;
}Board;
int main()
{
Board itemList[100];
char linestr[100];
int cnt=0;
string fileName;
cout<<"Please enter the file name, include the.txt"<<endl;
cin>>fileName;
ifstream ifs;
ifs.open(fileName.c_str());
if(ifs.fail())
{
cout<<"failed to open"<<endl;
}
else
{
while(ifs.getline(linestr,100))
{
string tmpstr(linestr);
int pos1=tmpstr.find(",");
int pos2=tmpstr.rfind(",");
itemList[cnt].type=tmpstr.substr(0,pos1);
itemList[cnt].condition=tmpstr.substr(pos1+1,pos2-pos1-1);
itemList[cnt].price=stod(tmpstr.substr(pos2+1));
cnt++;
}
}
for(int i=0;i<cnt;++i)
{
cout<<itemList[i].type<<" "<<itemList[i].condition<<" "<<itemList[i].price<<endl;
}
}
我根据你的代码改写了一个
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询