Sunday, April 3, 2011

Extract integer from char buffer

Hi

I have a very simple problem in C. I am reading a file linewise, and store it in a buffer

char line[80];

Each line has the following structure:

Timings results : 2215543
Timings results : 22155431
Timings results : 221554332
Timings results : 2215543

What I am trying to do, is to extract the integer value from this line. Does C here provide any simple function that allows me to do that?

Thanks

From stackoverflow
  • Yes - try atoi

       int n=atoi(str);
    

    In your example, you have a fixed prefix before the integer, so you could simply add an offset to szLine before passing it to atoi, e.g.

       int offset=strlen("Timings results : ");
       int timing=atoi(szLine + offset);
    

    Pretty efficient, but doesn't cope well with lines which aren't as expected. You could check each line first though:

       const char * prefix="Timings results : ";
       int offset=strlen(prefix);
       char * start=strstr(szLine, prefix);
       if (start)
       {
           int timing=atoi(start+offset);
    
           //do whatever you need to do
       }
       else
       {
           //line didn't match
       }
    

    You can also use sscanf for parsing lines like this, which makes for more concise code:

       int timing;
       sscanf(szLine, "Timings results : %d", &timing);
    

    Finally, see also Parsing Integer to String C for further ideas.

    Makis : You still have to parse the string because doesn't atoi() return 0 if your string starts with a non-numerical value?
    Adrian Panasiuk : `strtol` is better than `atoi` as it allows you to handle errors.
  • Can use sscanf per line, like:

    #include <stdio.h>
    int time;
    char* str = "Timings results : 120012";
    
    int n = sscanf(str, "Timings results : %d", &time);
    

    in this case n == 1 means success

0 comments:

Post a Comment