我已经在互联网上搜索了一段时间,但在我眼中找不到一个简单的解决方案。我想已经有人问过了:
我正在通过20.1
从文件中读取XYZ
或sscanf
,并将其保存在char *width_as_string
中。
所有功能都应在-std=c99
。
现在我想检查width_as_string
中的值是否为整数。如果为true,则应将其保存在int width
中。如果为false,则width
应保留值0
。
我的方法:
int width = 0;
if (isdigit(width_as_string)) {
width = atoi(width_as_string);
}
或者,将width_as_string
转换为int width
并将其转换回字符串。然后比较它是否相同。但我不确定如何实现这一目标。我已经尝试了itoa
。
isdigit
和itoa
等功能在std=c99
中无效,因此我无法使用它们。
感谢。
答案 0 :(得分:1)
答案 1 :(得分:1)
实际上,您可以在一开始就使用sscanf来检查数字是否为整数。像这样的东西
#include <stdio.h>
#include <string.h>
int
main (int argc, char *argv[])
{
int wc; // width to check
int w; // width
char *string = "20.1";
printf("string = %s\n", string);
if (strchr(string, '.') != NULL)
{
wc = 0;
printf("wc = %d\n", wc);
}
else if ((sscanf(string, "%d", &w)) > 0)
{
wc = w;
printf("wc = %d\n", wc);
} else w = 0;
return 0;
}
这是一个示例程序,当然,它首先在字符串中搜索&#34;。&#34;验证数字是否可以浮动并在这种情况下丢弃它,然后尝试读取整数,如果没有&#34;。&#34;被发现。
感谢ameyCU的建议
答案 2 :(得分:1)
仔细阅读 一些documentation of sscanf
。它返回一个计数,并接受%n
转换说明符,以给出到目前为止扫描的字符数(字节数)。也许你想要:
int endpos = 0;
int width = 0;
if (sscanf(width_as_string, "%d %n", &width, &endpos)>=1 && endpos>0) {
behappywith(width);
};
也许您还想在&& width_as_string[endpos]==(char)0
endpos>0
(以检查该数字是否为空格后缀,然后到达字符串的结尾)
您还可以考虑设置结束指针的标准strtol:
char*endp = NULL;
width = (int) strtol(width_as_string, &endp, 0);
if (endp>width_as_string && *endp==(char)0 && width>=0) {
behappywith(width);
}
*endp == (char)0
正在测试由strtol
填充的数字指针的结尾 - 是字符串指针的结束(因为字符串以零字节终止)。如果你想接受尾随空格,你可以更加花哨。
PS。实际上,您需要指定精确什么是可接受的输入(可能通过某种EBNF语法)。我们不知道您是否接受"1 "
或"2!"
或"3+4"
(作为C字符串)。