Roberto
Roberto

Reputation:

Extract integer from char buffer

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

Upvotes: 9

Views: 34453

Answers (2)

Joakim Elofsson
Joakim Elofsson

Reputation: 38284

Can use sscanf per line, like:

#include <stdio.h>
int time = -1;
char* str = "Timings results : 120012";

int n = sscanf(str, "Timings results : %d", &time);

in this case n == 1 means success

Upvotes: 19

Paul Dixon
Paul Dixon

Reputation: 301055

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.

Upvotes: 2

Related Questions