更新了atoi(string.c_str())的偶尔未处理的异常

Occasional unhandled exception with atoi(string.c_str()) Updated

本文关键字:异常 未处理 偶尔 str atoi string 更新      更新时间:2023-10-16

更新

我以为stoi(字符串)解决了这个问题,但它只起了一小会儿的作用。我在下面添加了splitString和解密的代码。

我偶尔会使用假定的相同值使用atoi()处理未处理的异常。

我的代码如下:

ifstream myfile ("Save.sav");
string line = "";
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
}
myfile.close();
line = StaticFunctions::decrypt(line);
}
vector<string> splitString = StaticFunctions::splitString(line, 's');
return atoi(splitString[0].c_str());

因此,它所做的是读取一个存储文件,然后对其进行解密,然后用每个s来分割字符串。调试时,保存文件始终相同,第一个值为3。

这种工作有时,可能每10次尝试。所以每10次尝试中有9次,我都会在。。。在内存位置。

监控转换后的值显示它总是返回3,然后应用程序不会崩溃,直到我开始游戏,这在代码中有点远。

如果我删除atoi并只返回3,则应用程序工作正常。

我试过strtod,但没有用。

谢谢,

  • 马库斯

SplitString代码:

vector<string> StaticFunctions::splitString(string str, char splitByThis)
{
vector<string> tempVector;
unsigned int pos = str.find(splitByThis);
unsigned int initialPos = 0;
// Decompose statement
while( pos != std::string::npos ) {
tempVector.push_back(str.substr( initialPos, pos - initialPos + 1 ) );
initialPos = pos + 1;
pos = str.find(splitByThis, initialPos );
}
// Add the last one
tempVector.push_back(str.substr(initialPos, std::min(pos, str.size()) - initialPos + 1));
return tempVector;

}

解密代码(非常简单):

string StaticFunctions::decrypt(string decryptThis)
{
for(int x = 0; x < decryptThis.length(); x++)
{
switch(decryptThis[x])
{
case  '*':
{
decryptThis[x] = '0';
break;
}
case  '?':
{
decryptThis[x] = '1';
break;
}
case  '!':
{
decryptThis[x] = '2';
break;
}
case  '=':
{
decryptThis[x] = '3';
break;
}
case  '#':
{
decryptThis[x] = '4';
break;
}
case  '^':
{
decryptThis[x] = '5';
break;
}
case  '%':
{
decryptThis[x] = '6';
break;
}
case  '+':
{
decryptThis[x] = '7';
break;
}
case  '-':
{
decryptThis[x] = '8';
break;
}
case  '"':
{
decryptThis[x] = '9';
break;
}
}
}
return decryptThis;
}

尝试使用strtol代替

strtol(splitString[0].c_str(),NULL,10);

stoi(string)而不是atoi(string.c_str())解决了这个问题。

更新:它没有解决问题。