Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse integer without appending char in C

Tags:

c

scanf

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);
    }
}
like image 686
Gastmon Avatar asked Apr 30 '17 20:04

Gastmon


Video Answer


1 Answers

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.

like image 182
Manav Dubey Avatar answered Sep 19 '22 02:09

Manav Dubey