C++atoi返回不正确的值
C++ atoi returning incorrect values
由于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 );
相关文章:
- 在C++中返回不正确的楼层函数值
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- wcslen() 在使用编译指示包时返回不正确的结果
- 乘法返回我的值不正确
- 为什么代码不能返回正确的值?
- 派生类继承的 getter,找不到返回正确值的方法
- 返回类型不正确
- 当我输入分数值时,它返回不正确的结果
- ifstream::read 不断返回不正确的值
- Strftime在iOS上返回一周中不正确的一天
- C++ 中的 MD5 实现返回不正确的摘要
- AccessibleObjectFromPoint() 返回一个不正确的对象
- C 程序不会返回正确的阶乘值
- C 从文件中读取FSTREAM数据不会返回正确的值.inputfile.tellg返回-1
- MSVC OSVersion 返回不正确的版本
- C++ GetModule文件名不会返回正确的字符串
- 'SystemParametersInfo'函数在获取桌面壁纸时返回不正确的值
- 创建 CTime @ 2am 不会返回正确的值(Windows CE,C++)
- c++winsock-recv()返回不正确且奇怪的缓冲区
- Winsock recv() 返回不正确的数据