parse integer without appending char in C

2019-02-22 07:59发布

问题:

I want to parse an integer but my following code also accepts Strings like "3b" which start as a number but have appended chars. How do I reject such Strings?

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

int main(int argc, char *argv[])
{
    int n;
    if(argc==2 && sscanf(argv[1], "%d", &n)==1 && n>0){
        f(n);
        return 0;
    }
    else{
        exit(EXIT_FAILURE);
    }
}

回答1:

For your problem, you can use strtol() function from the #include <stdlib.h> library.

How to use strtol(Sample code from tutorial points)

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

int main(){
   char str[30] = "2030300 This is test";
   char *ptr;
   long ret;

   ret = strtol(str, &ptr, 10);
   printf("The number(unsigned long integer) is %ld\n", ret);
   printf("String part is |%s|", ptr);

   return(0);
}

Inside the strtol, it scans str, stores the words in a pointer, then the base of the number being converted. If the base is between 2 and 36, it is used as the radix of the number. But I recommend putting zero where the 10 is so it will automatically pick the right number. The rest is stored in ret.



回答2:

The ctype.h library provides you the function isdigit(char) function that returns whether the char provided as argument is a digit or not.
You could iterate over argv[1] and check it this way.



标签: c scanf