Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding how to create atoi; How are characters compared?

Tags:

People also ask

How does atoi () work?

The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number.

How do you make an atoi function?

Write your own atoi() Parameters: The function accepts one parameter strn which refers to the string argument that is needed to be converted into its integer equivalent. Return Value: If strn is a valid input, then the function returns the equivalent integer number for the passed string number.

What is the meaning of atoi?

atoi is a function in the C programming language that converts a string into an integer numerical representation. atoi stands for ASCII to integer.


I am trying to improve my understanding of C++, pointer arithmetic especially. I use atoi pretty often, but I have rarely given thought as to how it works. Looking up how it is done, I understand it mostly, but there is one thing that I am confused about.

Here is an example of a solution I have found online:

int atoi( char* pStr ) 
{
  int iRetVal = 0; 

  if ( pStr )
  {
    while ( *pStr && *pStr <= '9' && *pStr >= '0' ) 
    {
      iRetVal = (iRetVal * 10) + (*pStr - '0');
      pStr++;
    }
  } 
  return iRetVal; 
} 

I think the main reason I have had a hard time grasping how atoi as been done in the past is the way characters are compared. The "while" statement is saying while the character exists, and the character is less-than-or-equal-to 9, and it is greater-than-or-equal-to 0 then do stuff. This statement says two things to me:

  1. Characters can be compared to other characters logically (but what is the returned value?).

Before I looked into this I suppose I knew it subconsciously but I never actually thought about it, but a '5' character is "smaller" than a '6' character in the same way that 5 is less than 6, so you can compare the characters as integers, essentially (for this intent).

  1. Somehow while (*sPtr) and *SPtr != 0 are different. This seems obvious to me, but I find that I cannot put it into words, which means I know this is true but I do not understand why.

Edit: I have no idea what the *pStr - '0' part would do.

Any help making sense of these observations would be very... helpful! Thanks!