使用sscanf从没有空格的字符串中提取整数

时间:2014-01-27 22:07:42

标签: c scanf

是否可以使用 sscanf从没有空格的字符串中提取数字? (我 仅使用 sscanf而不使用C的其他功能,因为我的代码为Neuron且仅使用{ {1}})。

例如:sscanfstring = "Hello[9]five[22]" 我不知道字符串是什么,我知道括号内有两个数字。

我想用string = "asdas[9]asda[22]"提取整数......是否可能?

2 个答案:

答案 0 :(得分:2)

Be sure to check the return value of `sscanf()`

#define StringJunk "%*[^0-9[]"
// Any string that does _not_ contain digits nor '['. 
// '*' implies don't save the result.

const char *str = "Hello[9]five[22]"
int num[2];
int cnt =  sscanf(str, StringJunk "[%d]" StringJunk "[%d]", &num[0], &num[1]);

if (cnt == 2) Success();
else if (cnt == EOF) EndOfFileOccurred();
else ScanningError();

迂腐检查会使用哨兵检查尾随垃圾。存在各种方法。

int i = 0;
int cnt = sscanf(str, " " StringJunk "[%d]" StringJunk "[%d] %n", 
    &num[0], &num[1], &i);
if (cnt == 2 && str[i] == '\0') Success();

答案 1 :(得分:0)

以下是我提出的建议:

#include <stdio.h>

int main(int argc, char *argv[]) {
    const char *test = "Hello[9]five[22]";
    const char *p;
    int num = 0;
    int spos1, spos2;

    if(argc>1)
        test = argv[1];

    p = test;
    while( *p ) {
        spos1 = spos2 = 0;
        if( sscanf(p, "%*[^[][%n%d]%n", &spos1, &num, &spos2) == 1) {
            printf("Found the number %d\n", num);
        }
        if( spos1 == 0 )
            p += 1;
        if( spos2 ) {
            p += spos2;
        } else {
            printf("Malformed number: no closing bracket.\n");
            p += spos1;
        }
    }
    return 0;
}
相关问题