9

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

2 Answers 2

19

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

You still have to parse the string because doesn't atoi() return 0 if your string starts with a non-numerical value?
strtol is better than atoi as it allows you to handle errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.