检查输入是否仅包含 C 中的数字

Checking if input contains digits only in C

我需要检查插入的输入(大小由用户确定的数组,意思是在 运行 时间内)是否仅包含数字 (C99)。 虽然我知道如何这样做,但在我看来这很笨拙,这导致我在这里问是否有更好的解决方案。我的 "idea" 是接收作为字符串数组的输入,然后 运行 对每个成员进行循环以检查它是否包含非数字字符。有什么更好的办法吗?

使用 getchar()(stdio.h) 读取输入以获得最佳性能,然后在读取输入时可以使用 isdigit() 检查当前字符是否为数字位于 ctype.h

所以,如果我正确理解你的问题,你读入了一行数组中的几行文本,即你有:

char **lines;
int count_lines, i;

count_lines = get_line_count_somehow();
lines = malloc(count_lines*sizeof(*lines));
for (i = 0; i < count_lines; i++)
    lines[i] = get_actual_line_somehow();

现在您想遍历每个字符串。我在这里假设 i 的每个值的 lines[i] 都是 '[=14=]' 终止的。

int contains_digits_only = 1;

for (i = 0; i < count_lines; i++)
{
    char *ptr = lines[i];
    while (*ptr)
    {
        if (!isdigit(*ptr));
        {
             contains_digits_only = 0;
             goto out;
        }
        ptr++;
    }
}
out:
do_something_with(contains_digits_only);