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

标签 c scanf

如果我有:

str1 = "str1s2"
str2 = "djfs1d2.3"

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

我试过:

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

但我只得到第一个数字:

n1 = 1
n2 = 1

最佳答案

使用 %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;
}

关于c - 如何通过 sscanf() 获取字符串中的最后一个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44088896/

相关文章:

c++ - 在开发国际象棋程序时,用给定的值初始化下面的方向数组有什么意义?

c++ - 'null' 和 'NULL' 相同吗?

c - 想要使用特定字符将字符串分隔为标记

C++ #include 外部函数问题

c - Scanf_s 读取错误的输入

c - 使用 UDP 套接字的多个 sendto()

c - 像空格这样的修饰符在 scanf 中起什么作用?

char - scanf 并将 char 保留为整数

c - While循环第二次忽略scanf

c - 终止 While 循环 scanf ("%c",&ch)