Thread: Best way to scan string for a number?

  1. #1
    Registered User
    Join Date
    Dec 2012
    Posts
    21

    Best way to scan string for a number?

    My string input can either be "-c123" or "-c 123".

    What's the best way to scan the string to get the number out?

  2. #2
    Registered User
    Join Date
    Sep 2012
    Posts
    355
    If you don't need tight control, try atoi().
    If you want tighter control of errors, prefer strtol().

    Read the function descriptions!!!

    Code:
    char input1[] = "-c123";
    char input2[] = "-c 123";
    int val1atoi = atoi(input1 + 2);
    int val2atoi = atoi(input2 + 2);
    
    char *err;
    errno = 0; int val1strtol = strtol(input1 + 2, &err, 10); /* test *err, val1strtol, and errno */
    errno = 0; int val2strtol = strtol(input2 + 2, &err, 10); /* test *err, val2strtol, and errno */
    You can also use sscanf() withy a littel more control than atoi() and a little less than strtol() ...
    Code:
    char input[] = "-c 123";
    int val;
    if (sscanf(input, "-c%d", &val) != 1) /* error */;
    All 3 funtions above properly ignore whitespace.
    Last edited by qny; 12-07-2012 at 08:19 AM.

  3. #3
    Registered User
    Join Date
    Dec 2012
    Posts
    21
    thanks a ton. I was messing around with sscanf() but didn't really wrap my head around it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 11-23-2012, 11:31 PM
  2. Best way to scan in a string
    By Matt Hintzke in forum C Programming
    Replies: 4
    Last Post: 02-02-2012, 05:33 PM
  3. Scan a string, present character
    By emdleb in forum C Programming
    Replies: 6
    Last Post: 02-11-2011, 09:21 AM
  4. scan a string
    By Max in forum C Programming
    Replies: 4
    Last Post: 12-02-2002, 03:26 PM