C++atoi返回不正确的值

C++ atoi returning incorrect values

本文关键字:不正确 返回 C++atoi      更新时间:2023-10-16

由于https://stackoverflow.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是否不正确?

问题是您正在用:重新映射相同的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

使用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 );