我试图从文件中获取一些信息,然后将其输入到三个单独的数组中。信息采用以下格式:teanmane,概率1,概率2现在,它从文件输入中获取信息,并输入到三个单独的字符串中,然后给出上述错误并转储核心并退出。我不明白为什么。以下是代码。
string teamname[8];
double p1[8];
double p2[8];
void input()
{
ifstream file;
char fileName[20];
cin>>fileName;
int arrindex=0;
file.open(fileName);
while(!file.eof())
{
int len;
string line;
string name;
string buffer;
string buffer2;
stringstream temp;
stringstream temp2;
stringstream temp3;
double probTg;
double probFg;
getline(file, line);
cout<<line<<endl;
temp<<line;
temp>>name;
len=name.length();
name.resize((len-1));
name[len]='\0';
temp>>buffer;
buffer.resize(4);
temp2<<buffer;
temp2>>probTg;
temp>>buffer2;
buffer2.resize(4);
temp3<<buffer2;
temp3>>probFg;
if(arrindex<8)
{
teamname[arrindex]=name;
cout<<teamname[arrindex];
p1[arrindex]=probTg;
cout<<p1[arrindex];
p2[arrindex]=probFg;
cout<<p2[arrindex];
arrindex++;
}
}
file.close();
}
我认为您的问题是您正在将stl惯用语与cdoms混合使用。
下面的代码将您的行解析替换为scanf。我认为这比用<<和>>运算符完成的相同代码要清晰得多。
string teamname[8];
double p1[8];
double p2[8];
void input()
{
ifstream file(filename);
if (file.bad()) return 1;
int ix = 0;
while (ix < 8) {
if (file.eof())
break;
string line;
getline(file, line);
char * team;
double d1, d2;
int fields = sscanf(line.c_str(), "%a[a-zA-Z], %lf, %lf", &team, &p1[ix], &p2[ix]);
if (fields >= 1) {
teamname[ix] = team;
free(team);
}
++ix;
}
file.close();
for (ix = 0; ix < 8; ++ix) {
printf("%s %f %f\n", teamname[ix].c_str(), p1[ix], p2[ix]);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句