【问题标题】:C: Check if a string is an integer and save itC:检查字符串是否为整数并保存
【发布时间】:2015-12-26 13:24:00
【问题描述】:

我已经在互联网上搜索了一段时间,但是对于我眼中的一个实际上很简单的问题,我没有找到一个简单的解决方案。我想它已经被问过了:

我正在通过sscanf 从文件中读取20.1XYZ 之类的值并将其保存在char *width_as_string 中。

所有函数都应该在-std=c99中有效。

现在我想检查width_as_string 中的值是否为整数。如果为真,则应保存在int width 中。如果为 false,width 应保留值 0

我的方法:

int width = 0;
if (isdigit(width_as_string)) {
    width = atoi(width_as_string);
}

或者,将width_as_string 转换为int width 并将其转换回字符串。然后比较是否相同。但我不确定如何实现这一目标。我已经尝试过itoa

isdigititoa 之类的函数在 std=c99 中无效,因此我无法使用它们。

谢谢。

【问题讨论】:

  • 你认为这里的“整数”是什么?
  • @MikeCAT 20.1 不是整数,是吗?宽度值只能包含 0-9 的数字 :)
  • 那么-123在这里不被视为整数吗?
  • isdigit 在 C99 中肯定是有效的。 itoa,没那么多。使用strtol

标签: c


【解决方案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);
};

也许您还想在endpos>0 之后添加&& width_as_string[endpos]==(char)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 字符串)为您所接受。

【讨论】:

  • 建议if (endp != width_as_string && ...检测" "
  • @chux: 除非width_as_string 以非数字字符开始(如/),通常情况下endp != width_as_string 可能不会带来很多。
  • @BasileStarynkevitch 第二个效果很好,谢谢!
  • 1) if (endp 测试没有提供任何我能看到的东西。 strtol() 转换一个字符串,当函数完成时,endp 将指向该字符串中的某个位置,所以strtol() 不会形成一个NULLendp。 2)当它是""时,这个答案接受width_as_string
【解决方案2】:

strtol 怎么样?

如果出现问题,这会给出一个明确的返回值,我认为这就是你要找的

http://www.cplusplus.com/reference/cstdlib/strtol/

【讨论】:

  • 谢谢,但我没有成功实现这个功能:(
  • @michithebest 实施是什么意思?这是一个标准功能,你必须使用它。
【解决方案3】:

其实你可以在一开始就使用 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;
}

当然,这是一个示例程序,它首先在字符串中搜索“.”。验证数字是否可以是浮点数并在这种情况下丢弃它,然后尝试读取一个整数,如果没有“。”被发现。

感谢ameyCU的建议,修改了

Reference page for sscanf

【讨论】:

  • if ((sscanf(width_string, "%d", &amp;width_to_check)) &gt; 0) { width = width_to_check; } else width = 0; 这样尝试过,但它接受20.1 之类的值,然后将它们切成20 :(
  • @michithebest 在读取变量中的值之前,使用strchrstrstr 函数检查字符串中是否存在.
  • 但是如果值为20,120abc 是否仍然有效?在这两种情况下,width 应保持为0
  • 不,因为它现在仍然存在这些问题,所以这不是正确的答案:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-13
  • 2016-02-18
  • 2016-10-23
  • 1970-01-01
  • 2020-07-13
  • 2012-04-27
相关资源
最近更新 更多