Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ atoi returning incorrect values

Tags:

c++

atoi

The problem seems fixed now, thanks to https://stackoverflow.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.

so I searched around before asking this and I can't seem to find anyone with a similar case to mine, so I'll ask here.

I have a config file, which contains ids that aren't in incremental order, example:

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

Now, the issue is raised when ever I attempt to read these values from a file, and parse them to an int using atoi, when I convert it to an int, 517 would become 202 or some random number like that, is this normal behavior? Here's an example of how I'm parsing the file and converting the ID's:

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

Would using atoi in this case be incorrect?

like image 469
Lynxaa Avatar asked Nov 16 '25 05:11

Lynxaa


1 Answers

The trouble is you're resplitting the same line variable with :, so x2[0] will contain "48|0". This isn't a valid input to atoi.

Try this instead:

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());

This should work better, as you're passing a valid input to split the second time round.

like image 153
Baldrick Avatar answered Nov 18 '25 18:11

Baldrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!