我正在刷新我的 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/