I have to rewrite the atoi function - that is, convert a string given by a command line argument and convert it to an integer. It works for single digit numbers, but when you give it two or more digits, it only converts the first number. I'm not sure what I'm doing wrong, as the concept seems simple. Take in a string, change it's type, print it on the screen with a new format character. Right?

#include <stdio.h>

int myatoi( char *x );

int main( int argc, char *argv[] ) {

    char *x = argv[1];
    int y;

    printf( "Character :   %c\n", *x );

    y = myatoi( x );

    printf( "Integer   :   %d\n", y );

    return 0;

}

int myatoi( char *x ) {

    int y = ( *x - 48 );

    return y;

}

*x is a way to access the first element of the character array x .

To do what you want properly, you need to iterate over all elements of the string and convert each in turn while properly maintaining the resulting value. As a hint, you may think of the following:

char * string = "1234";
int value = 0;

for i in string:
   value = left_shift(value) + i;

As L7sqr implied:

int myatoi( char *x ) {

    int y = ( *x - 48 );  // convert the first character into an integer
                          // What about the second, third,... characters?
    return y;
}

Think loop...

I read more in my textbook and found the solution on my own. You pretty much covered it. I cast each character as an integer and stored in an array that was malloc'd to the strlen of the input. Each was then multiplied by 10^j, using strlen-1 as a starting point and looping down.

Thanks for your help though!

If anyone needs the source to my solution, post a response.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.