C++ atoi 返回不正确的值

C++ atoi returning incorrect values

The problem seems fixed now, thanks to https://whosebug.com/users/2609288/baldrick for his response, he pointed out the main issue that led me to think atoi was returning the wrong value. Since I was printing the results into a console window using AllocConsole, I guess cout was printing the results incorrectly, after printing a few integers with high values, this does indeed seem to be the case.

所以在问这个问题之前我搜索了一下,似乎找不到任何人和我有类似的情况,所以我会在这里问一下。

我有一个配置文件,其中包含非递增顺序的 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 );