C++ 中的文件 IO 出错。在抛出 'std::length_error' 的实例后调用的终止 what(): basic_string::调整大小

Error with file IO in c++. terminate called after throwing an instance of 'std::length_error' what(): basic_string::resize

本文关键字:what 调用 终止 调整 string basic 实例 length 出错 IO 文件      更新时间:2023-10-16

我试图从一个文件中获取一些信息,然后将其输入到三个独立的数组中。信息的格式如下:teanmane,probability 1,probability 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]='';
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习惯用法与c idom混合在一起。

下面的代码将您的行解析替换为scanf。我认为它比用<lt;和>>运算符。

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 %fn", teamname[ix].c_str(), p1[ix], p2[ix]);
}
}

这对我来说似乎是个问题。你只需要resize字符串,然后放一些超出大小的东西。实际上比分配的大小多了两个。

如果分配是20,则下面的语句尝试放入第22个内存位置。

name.resize((len-1));
name[len]='';
相关文章: