【问题标题】:Using sscanf to extract integers embedded in parenthesis使用 sscanf 提取括号中嵌入的整数
【发布时间】:2016-02-03 03:52:03
【问题描述】:

我想使用 sscanf 从 c 中的字符串中提取。我有一个刺痛,它的形式总是(int)string,即(10)foo。我试过这种方法没有运气:

#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);
}

输出:

a value = 0
Reg value = 

【问题讨论】:

  • 你忘了%d吗?

标签: c string int character scanf


【解决方案1】:

您的格式说明符错误。您应该将警告级别调高,以便从编译器获得有用的反馈。当我使用gcc -Wall 编译你的程序时,我得到:

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);

我不确定您希望该格式字符串做什么,但它不会做您想要的。您可以使用更简单的格式。

其他要点:

a 传递给scanf 系列函数将不起作用。您需要通过&amp;a

始终检查scanf 系列函数的返回值,以确保输入成功。

这是main 的改进版本,应该可以使用。它对我有用。

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;
}

【讨论】:

    【解决方案2】:

    我会这样改变你的 sscanf 行:

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

    请注意:您必须将整数的指针传递给 sscanf()...

    【讨论】:

    • 我很欣赏它的简洁性。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 2022-12-23
    • 2011-08-10
    • 2019-02-07
    • 2019-07-22
    • 2021-10-30
    相关资源
    最近更新 更多