Using sscanf to extract integers embedded in parenthesis

时间:2016-02-03 03:52:04

标签: c string int character scanf

I want to extract from a string in c using sscanf. I have a have a sting that will always have the form (int)string i.e. (10)foo. I have tried this approach with no luck:

#include <stdio.h>

int main(){
    char buf[128] = "(10)foo",
         reg[4]; 
    int a;
    sscanf(buf, "([^'(']%[^')']) %s",a, reg);
    printf("a value = %d\nReg value = %s\n", a, reg);
}

output:

a value = 0
Reg value = 

2 个答案:

答案 0 :(得分:2)

Your format specifier is wrong. You should turn the warning level higher to get useful feedback from your compiler. When I compile your program using gcc -Wall, I get:

soc.c: In function ‘main’:
soc.c:7:4: warning: format ‘%[^')'’ expects argument of type ‘char *’, but argument 3 has type ‘int’ [-Wformat=]
    sscanf(buf, "([^'(']%[^')']) %s",a, reg);
    ^
soc.c:7:10: warning: ‘a’ is used uninitialized in this function [-Wuninitialized]
    sscanf(buf, "([^'(']%[^')']) %s",a, reg);

I am not sure what you expected that format string to do but it's not going to do what you want it to. You can use a much simpler format.

Other points:

Passing a to scanf family of functions will not work. You will need to pass &a.

Always check the return value of scanf family of functions to make sure that input was successful.

Here's an improved version of main that should work. It works for me.

int main(){
   char buf[128] = "(10)foo",
        reg[4]; 
   int a;
   int n = sscanf(buf, "(%d) %s", &a, reg);
   if ( n != 2 )
   {
      printf("Problem in sscanf\n");
   }
   else
   {
      printf("a value = %d\nReg value = %s\n", a, reg);
   }
   return 0;
}

答案 1 :(得分:1)

I would change your sscanf line this way:

sscanf(buf, "(%d)%s",&a, reg);

Please note: you have to pass the pointer of your integer to sscanf()...