c - 在 C 中的扫描字符上运行 isdigit()

标签 c validation scanf

我正在刷新我的 C 技能,并且在编写一个简单的程序时遇到了一些困难。这是:

#include <stdio.h>
#include <ctype.h> // for isdigit()
#include <stdlib.h> // for atoi()

int main (int argc, const char * argv[])
{
    // first read in # of file events to follow, if not an int,
    // complain & abort
    char *input;
    input = malloc(2); // input[0] holds the character
                       // input[1] holds the terminator

    int numLines = 0;
    scanf("%c", &input);
    if (isdigit((int)input)) {
        numLines = atoi(input);
    } else {
        printf("First line of input must be int type! Aborting...\n");
        return 1;
    }
    //...
}

问题是,即使我输入一个数字(即 2),它仍然输出中止消息并退出:

2
First line of input must be int type! Aborting...

我很难弄清楚为什么它会这样,以及我应该采取什么措施来解决这个问题。难道“%c”说明符不应该告诉编译器将输入作为 ANSI 字符接收,然后 isdigit() 应该正确地将其解释为整数吗?

提前致谢!

最佳答案

更改此:

scanf("%c", &input);
if (isdigit((int)input)) {

对此:

scanf("%c", input);
if (isdigit(input[0])) {

现在,您正在覆盖指针本身,而不是写入分配的内存。

此外,您需要以空终止:

input[1] = '\0';

此外,没有必要为此分配内存。您只需:

char input[] = " ";
scanf("%c", input);
if (isdigit(input[0])) {
    numLines = atoi(input);

或者:

char input;
scanf("%c", &input);
if (isdigit(input)) {
    numLines = input - '0';

关于c - 在 C 中的扫描字符上运行 isdigit(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8707946/

相关文章:

C 推弹测试

C 将文件指针传递给函数

ruby-on-rails - Rails 3 自定义验证和 shoulda

C 跳过函数的一个命令?

c - 使用 fscanf(file, %x, x) 并在 C 中将十六进制转换为整数

c - 多维数组和指针数组的区别

c - Borland C rand() 的实现

javascript - 用于检查输入是否不为空的 Jquery 脚本。空格键问题

javascript - 如何使用 javascript 验证 html 5 输入类型日期?

c - 如何分配一个字符串值