Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different results using atoi

Tags:

c++

Could someone explain why those calls are not returning the same expected result?

unsigned int GetDigit(const string& s, unsigned int pos)
{
      // Works as intended
      char c = s[pos];
      return atoi(&c);

      // doesn't give expected results
      return atoi(&s[pos]);
      return atoi(&static_cast<char>(s[pos]));
      return atoi(&char(s[pos]));
}

Remark: I'm not looking for the best way to convert a char to an int.

like image 465
Ronald McBean Avatar asked Oct 24 '11 09:10

Ronald McBean


People also ask

What does atoi function return?

The atoi() function returns an int value that is produced by interpreting the input characters as a number. The return value is 0 if the function cannot convert the input to a value of that type. The return value is undefined in the case of an overflow.

What does atoi return if its not a number?

The atoi() function returns the converted integer value if the execution is successful. If the passed string is not convertible to an integer, it will return a zero.

What is the difference between atoi and stoi?

First, atoi() converts C strings (null-terminated character arrays) to an integer, while stoi() converts the C++ string to an integer. Second, the atoi() function will silently fail if the string is not convertible to an int , while the stoi() function will simply throw an exception.


1 Answers

None of your attempts are correct, including the "works as intended" one (it just happened to work by accident). For starters, atoi() requires a NUL-terminated string, which you are not providing.

How about the following:

unsigned int GetDigit(const string& s, unsigned int pos)
{
      return s[pos] - '0';
}

This assumes that you know that s[pos] is a valid decimal digit. If you don't, some error checking is in order.

like image 162
NPE Avatar answered Sep 17 '22 22:09

NPE