Search code examples
ccs50atoi

How does one correctly format the atoi function?


I'm trying to acquaint myself with the atoi function, so I wrote a basic programme using it, but I'm having some problems:

#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>

int main(void)
{
    string s = get_string("String:");
    int i = get_int("Integer:");
    int a = atoi(s[1]);
    int j = i + a;
    
    printf("%i\n", j);
}

When I try to compile it, I get the error message "incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Werror,-Wint-conversion]". This seems to suggest that it wants something to do with a char, but from what I've read, I was under the impression that atoi was used with strings. If someone could explain where I'm going wrong, I'd be very thankful


Solution

  • You're passing a char(assuming string is a typedef for char*) by indexing the string and it wants you to pass a char*. So just pass the full string:

    #include <stdio.h>
    #include <cs50.h>
    #include <stdlib.h>
    
    int main(void)
    {
        string s = get_string("String:");
        int i = get_int("Integer:");
        int a = atoi(s);
        int j = i + a;
        
        printf("%i\n", j);
    }