首页 > 解决方案 > 忽略带字母的数字

问题描述

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

int main(void)
{
  const char *str = "11 2 3 5a";
  int i = 0;
  unsigned int count = 0, tmp = 0;

  printf("%s\n", str);

  while (sscanf(&str[count], "%d %n", &i, &tmp) != EOF) {
    if (!isdigit(str[count])) break;
    count += tmp;
    printf("number %d\n", i);
  }

  return 0;
}  

我有类似的东西,但这仍然在抓取5. 如何让它忽略带有字母的数字?所以上面的str例子应该打印 11 2 3 而不是11 2 3 5a

标签: c

解决方案


最初将您的值作为子字符串读取,然后strtol与 end-marker 选项一起使用来确定刚刚读取的子字符串是否完全转换为整数(即​​它是否落在字符串终止符上以完成处理)。

它或多或少看起来像这样:

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

int main(void)
{
    const char * str = "11 2 3 5a";
    unsigned int count = 0, tmp = 0;
    
    char s[ strlen(str) + 1 ];
    
    printf("%s\n", str);
    while (sscanf(str+count, "%s%n", s, &tmp))
    {
        count += tmp;
        char *end = NULL;
        long i = strtol(s, &end, 10);
        if (end && *end)
            break;
        printf("number %ld\n", i);
    }
    
    return 0;
}

输出

number 11
number 2
number 3

推荐阅读