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

//Remembers n
int n = *argv[1];

I'm trying to access the value n as an integer. However, when I do this, n stores the ASCII code for the number (I think!). I have tried using atoi, and it worked, but I feel like it is cheating and would also like to know how to convert without using the CS50 function

2 Answers 2

0

The atoi() function is not cheating and it is not a CS50 function. It is a standard library function for converting a string representation of an integer to an actual integer so that it can be used. There is an entire family of related functions. You can google them at your leisure and learn more.

You should get in the habit of exploring any and all of the various c functions, types, etc., using man pages or google searches as you go along. It's the best way to learn about them.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1

The atoi () function is extremely useful and makes our code look clean, if you have any curiosity to know how to implement it, here is a function that emulates in part the atoi () function:

int strToInt (const char string[])
{
    int i, intValue, result = 0;

    for ( i = 0; string[i] >= '0' && string[i] <= '9'; ++i )
    {
        intValue = string[i] - '0';
        result = result * 10 + intValue;
    }

    return result;
}

By the way the code is not mine, it is a well-known algorithm in computer science

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .