c - 忽略带字母的数字
问题描述
#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
解决方案
最初将您的值作为子字符串读取,然后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
推荐阅读
- node.js - 私有 Linux 主机上的 Node.js 应用程序
- java - 如何将参数传递给已经运行的 java 程序
- regex - 如何在 RegEx 下方放置条件?
- c++ - 0xC0000005:访问冲突读取位置0x0000000000000008
- android - 有没有办法从谷歌地图中删除图标和标签,并为地点添加自定义图标和标签?
- admin-on-rest - 如何在 Edit 中提供自定义重定向到 SimpleForm?
- c# - 在一个命令中创建多个 sql 查询
- android - Android - 获取用户手机的国际电话号码
- android - 获取设备总内部存储器大小
- react-native - this.props.data.map 出现未定义错误