更新
我以为 stoi(string) 解决了这个问题,但它只工作了一段时间。 我在下面添加了 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 但没有帮助。
谢谢
- 马库斯
分割字符串代码:
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);
关于c++ - atoi(string.c_str()) 偶尔出现未处理的异常已更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12597177/