Parse integer without adding char in C

I want to parse an integer, but my next code also accepts strings like "3b" that start as a number but have characters added. How can I refuse such lines?

#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);
    }
}
+6
source share
2 answers

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

How to use strtol( Sample code from training 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);
}

strtol str, , . 2 36, . , 10, . ret.

+4

ctype.h isdigit (char), char .
argv [1] .

0

Source: https://habr.com/ru/post/1016905/


All Articles