如何检查输入是否为C中的数字? [英] how to check if the input is a number or not in C?
本文介绍了如何检查输入是否为C中的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C的main函数中:
In the main function of C:
void main(int argc, char **argv)
{
// do something here
}
在命令行中,我们将输入任意数字,例如1
或2
作为输入,但它会被视为argv参数的char数组,但如何确保输入是数字,以防人们输入 hello
或 c
?
In the command line, we will type any number for example 1
or 2
as input, but it will be treated as char array for the parameter of argv, but how to make sure the input is a number, in case people typed hello
or c
?
推荐答案
另一种方法是使用 isdigit 函数.下面是它的代码:
Another way of doing it is by using isdigit function. Below is the code for it:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXINPUT 100
int main()
{
char input[MAXINPUT] = "";
int length,i;
scanf ("%s", input);
length = strlen (input);
for (i=0;i<length; i++)
if (!isdigit(input[i]))
{
printf ("Entered input is not a number\n");
exit(1);
}
printf ("Given input is a number\n");
}
这篇关于如何检查输入是否为C中的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文