Search code examples
cstringatoi

Using atoi to check string


i am trying to use atoi to convert a string into an int, and then check if the string was indeed all integers.

Here is my code:

printf("Please input the port: ");
scanf("%s",port_number);
int i = atoi(port_number);
if(i != port_number)
{
    errno = ERR_INVALID_PARAM;                  
    printf("Error invalid port number\n");
}

However, even when my string "port_number" is an integer, it still goes in the if statement? Any help?


Solution

  • I'm assuming that port_number is of type char *.

    The if statement you have there is comparing the address of the port_number C string with value of i, and I don't think that's what you want to do.

    If you want to use ctype.h, then you can use the function "isdigit()" to check each element of port_number. Otherwise, the next best thing is to cycle through port_number, and figure out if each element is between ascii char '0' and '9', to make sure that the port number is entered correctly.