使用sscanf会提取字符串整数无空格

问题描述 投票:-1回答:2

是否有可能只使用sscanf没有空格来提取一个字符串的数字? (我只用sscanfC没有其他的功能,因为我的代码是Neuron,它仅使用sscanf)。

例如:string = "Hello[9]five[22]"string = "asdas[9]asda[22]"我不知道什么是字符串,我所知道的有两个数字被括号括起来。

我想sscanf提取整数...这可能吗?

c scanf
2个回答
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();

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.