如何通过sscanf()获取字符串中的最后一个数字?

时间:2017-05-20 17:27:33

标签: c scanf

如果我有:

sscanf(str1, "%*[^0-9]%d", &n1);
sscanf(str2, "%*[^0-9]%d", &n2);

如何通过sscanf()获取字符串中的最后一个数字?

我试过了:

n1 = 1
n2 = 1

但我只得到第一个数字:

 # log transform 
    log.ir <- log(iris[, 1:4])
    ir.species <- iris[, 5]

 
# apply PCA - scale. = TRUE is highly 
# advisable, but default is FALSE. 
ir.pca <- prcomp(log.ir,
                 center = TRUE,
                 scale. = TRUE) 

library(devtools)
install_github("ggbiplot", "vqv")
 
library(ggbiplot)
g <- ggbiplot(ir.pca, obs.scale = 1, var.scale = 1, 
              groups = ir.species, ellipse = TRUE, 
              circle = TRUE)
g <- g + scale_color_discrete(name = '')
g <- g + theme(legend.direction = 'horizontal', 
               legend.position = 'top')
print(g)

3 个答案:

答案 0 :(得分:3)

使用%n说明符存储扫描处理的字符数,您可以遍历字符串,直到scanf失败。

#include <stdio.h>

int main ( ) {
    char str2[] = "2to3";
    int span = 0;
    int index = 0;
    int lastvalue = 0;
    int value = 0;

    if ( 1 == sscanf ( &str2[index], "%d%n", &value, &span)) {
        index += span;
        lastvalue = value;
    }
    while ( 1 == sscanf ( &str2[index], "%*[^0-9]%d%n", &value, &span)) {
        index += span;
        lastvalue = value;
    }
    printf ( "last value = %d\n", lastvalue);
    return 0;
}

答案 1 :(得分:2)

我个人认为,只用scanf模式来阐述一个容易表达错误的错误。我宁愿使用一个单独的循环,它从字符串的末尾向开头迭代,并将指针放在最后一个数字处:

#include <stdio.h>
#include <ctype.h>

// extracts the last positive integral value of string s
// returns...
// on success, the int value scanned
// -1, if the string is null, empty, or not terminated by a number
int extractLastIntegral(const char* s) {
    int value = -1;
    if (s && *s) {  // don't parse null and empty strings
        const char *scanstr = s + strlen(s) - 1;
        while (scanstr > s && isdigit(*(scanstr-1))) {
            scanstr--;
        }
        sscanf(scanstr,"%d", &value);
    }
    return value;
}

int main ( ) {

    const char* teststrings[] = { "str1s2", "djfs1d2.3", "asdf3asd", "asd", "", NULL};
    ;
    for (const char** teststring=teststrings;*teststring;teststring++) {
        printf("string '%s' scans %d\n",*teststring,extractLastIntegral(*teststring));
    }
    return 0;
}

答案 2 :(得分:-1)

迭代直到你没有得到一个数字。 (可能更容易和更清晰的代码使用字符指针并从末尾向后遍历字符串,直到找到一个数字,然后继续向后直到找到非数字,然后从那里找到scanf。)

char *cp = str1;
int nc;
while(sscanf(cp, "%*[^0-9]%d%n", &n1, &nc) == 1) cp+=nc;
printf("n1: %d\n", n1);