Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

You need to do some error-checking on the string coming in before you convert it to an int. You may want to try the strtol() function. It checks whether a string can be converted to a long int. It returns either the converted value, or zero if the string cannot be converted.

the second arg to strtol() is a char**. After the function finishes, it points to the first character in the string that is NOT a legal number character. So if it points anywhere before the end of the string, then the conversion failed.

http://www.tutorialspoint.com/c_standard_library/c_function_strtol.htm

Think about what you are comparing there:

if(i != port_number)
{
    //code
}

i is of type int and port_number is a char*.

char *check = strdup(port_number);
sprintf(check, "%i", i);
if(strcmp(check, port_number))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top