C++ atoi 返回不正确的值

Posted

技术标签:

【中文标题】C++ atoi 返回不正确的值【英文标题】:C++ atoi returning incorrect values 【发布时间】:2015-12-08 14:52:11 【问题描述】:

现在问题似乎已解决,感谢https://***.com/users/2609288/baldrick 的回复,他指出了导致我认为 atoi 返回错误值的主要问题。 由于我使用 AllocConsole 将结果打印到控制台窗口中,我猜 cout 打印结果不正确,在打印了一些具有高值的整数之后,似乎确实如此。

所以在问这个之前我四处搜寻,似乎找不到与我的情况相似的人,所以我会在这里问。

我有一个配置文件,其中包含不按递增顺序排列的 id,例如:

48|0:0:0.001:0
49|0:0:0.001:0
59|0:0:0.001:0
60|497:0:0.001:0
61|504:0:0.001:1
63|0:0:0.001:0
500|0:0:0.001:0
505|0:0:0.001:0
506|0:0:0.001:0
507|0:0:0.001:0
508|0:0:0.001:0
509|0:0:0.001:0
512|0:0:0.001:0
515|0:0:0.001:0
516|0:0:0.001:0
517|415:132:0.001:1

现在,当我尝试从文件中读取这些值并使用 atoi 将它们解析为 int 时,就会出现问题,当我将其转换为 int 时,517 将变为 202 或类似的随机数,是这种正常行为?这是我如何解析文件和转换 ID 的示例:

std::vector<std::string> x = split(line, '|');
int id = atoi(x[0].c_str());
cout << id << " ";
std::vector<std::string> x2 = split(line, ':');
int kit = atoi(x2[0].c_str());
cout << kit << " ";
int seed = atoi(x2[1].c_str());
cout << seed << " ";
int wear = atoi(x2[2].c_str());
cout << wear << " ";
int stat = atoi(x2[3].c_str());
cout << stat << endl;
this->ParseSkin(id, kit, seed, wear, stat);

在这种情况下使用 atoi 会不正确吗?

【问题讨论】:

您确定split 工作正常吗?如果你只是打印出x[0] 是否正确? 它按预期工作,我在没有使用 atoi 的情况下打印了原始拆分值,它们都是正确的并且与文件内容匹配。 这就是我们需要 MCVE 的原因...... 您正在对十进制数使用 atoi()! (穿) 另外,你用: 重新分割同一行,所以x2[0] 将包含“48|0”。这不是atoi 的有效输入。应该是x[1]你第二次分裂。 【参考方案1】:

问题在于您将相同的line 变量与: 重新拆分,因此x2[0] 将包含“48|0”。这不是atoi 的有效输入。

试试这个:

std::vector<std::string> x = split(line, '|');
int id = atoi(x[0].c_str());
cout << id << " ";
std::vector<std::string> x2 = split(x[1], ':');
int kit = atoi(x2[0].c_str());

这应该会更好,因为您第二次将有效输入传递给split

【讨论】:

【参考方案2】:

使用strtol 代替atoi。它可以在任何非数字字符处停止。试试这个:

char * str = line;
id = strtol( str, &str, 10 ); str++;
kit = strtol( str, &str, 10 ); str++;
seed = strtol( str, &str, 10 ); str++;
wear = strtol( str, &str, 10 ); str++;
stat = strtol( str, &str, 10 );

【讨论】:

同样的结果,517 -> 205 @Lynxaa 没有splitstrtol 类似于使用第二个参数拆分。 @Lynxaa :) 我从不使用 cincout,但人们没有得到这个建议。 woops 误删,“好像已经修复了,永远不要相信 cout”

以上是关于C++ atoi 返回不正确的值的主要内容,如果未能解决你的问题,请参考以下文章

(C++) 在同一个类中调用时,取消引用的指针返回正确的值,从 main 调用时返回 0

从lua的c源码了解lua栈结构和函数调用流程

C++返回的数组值不正确

为啥 longLongValue 返回不正确的值

为啥 sin() 不返回正确的值?

从 C++ 函数与 Python 函数返回的值不一致,用于偏斜正态分布