返回atoi() - C函数

时间:2015-12-06 22:01:08

标签: c atoi

我有随机字符串,我想对它们进行排序。我需要找到只包含数字的数字(如xyz ...,x,y,z是数字);使用什么功能?

我试过了atoi("3=fyth433")。但是返回3。我希望它返回0一个字符串,其中包含无法解析为整数的字符。

1 个答案:

答案 0 :(得分:2)

您可以使用简单的测试:

if (*buf && buf[strspn(buf, "0123456789")] == '\0') {
    /* buf only contains decimal digits */
}

strspn()返回第一个参数开头的字符数,该字符与第二个字符串中的一个字符匹配。 *buf上的额外测试避免匹配空字符串。 空字符串只包含数字,因为它根本不包含任何内容。

如果buf读取fgets,您会检查'\n'而不是'\0',但正如chux正确指出的那样,如果最后一行不以换行结束:

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

...

char line[256];
while (fgets(line, sizeof line, stdin)) {
    size_t ndigits = strspn(line, "0123456789");
    if (ndigits > 0 && (line[ndigits] == '\n' || line[ndigits] == '\0')) {
        /* line only contains decimal digits */
    } else {
        /* line is empty or contains at least one non digit character */
    }
}

您还可以使用isdigit()中的<ctype.h>函数,但必须注意不要直接传递char值,因为它们可能是负数,从而调用未定义的行为。这是另一种选择:

int string_has_only_digits(const char *str) {
    if (!*str) // empty string
        return 0;
    while (isdigit((unsigned char)*str))
        str++;
    return *str == '\0';
}

您无法使用strtol,因为它接受初始空白序列和可选符号。