So...I know that the atoi function in the C++ standard library is supposed to convert a string into an integer...how does it work?...(I\'m trying to learn stuff and I was ju
Basically by subtracting ASCII zero ('0') and checking if it is a digit or not. You need to know the position:
#include
#include
#include
int atoi( const char* nptr )
{
int result = 0;
int position = 1;
const char* p = nptr;
while( *p )
{
++p;
}
for( --p; p >= nptr; p-- )
{
if( *p < 0x30 || *p > 0x39 )
{
break;
}
else
{
result += (position) * (*p - 0x30);
position *= 10;
}
}
result = ((nptr[0] == '-')? -result : result);
return result;
}
int main()
{
char buffer[BUFSIZ] = {0};
printf( "Enter an integer: " );
fgets( buffer, BUFSIZ, stdin );
buffer[strlen(buffer)-1] = 0;
printf( "You entered %d\n", atoi( buffer ) );
return 0;
}