在C的主要功能中:
void main(int argc, char **argv)
{
// do something here
}
在命令行中,我们将输入任何数字,例如1
或2
作为输入,但是对于 argv 的参数,它将被视为 char 数组,但是如何确保输入是数字,以防人们输入hello
or c
?
另一种方法是使用 isdigit 函数。下面是它的代码:
#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");
}
您可以使用类似的函数strtol()
将字符数组转换为长整数。
它有一个参数,这是一种检测未正确转换的第一个字符的方法。如果这不是字符串的结尾,那么你就有问题了。
有关示例,请参见以下程序:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[]) {
int i;
long val;
char *next;
// Process each argument given.
for (i = 1; i < argc; i++) {
// Get value with failure detection.
val = strtol (argv[i], &next, 10);
// Check for empty string and characters left after conversion.
if ((next == argv[i]) || (*next != '\0')) {
printf ("'%s' is not valid\n", argv[i]);
} else {
printf ("'%s' gives %ld\n", argv[i], val);
}
}
return 0;
}
运行这个,你可以看到它在运行:
pax> testprog hello "" 42 12.2 77x
'hello' is not valid
'' is not valid
'42' gives 42
'12.2' is not valid
'77x' is not valid
使用scanf
非常简单,这是一个例子:
if (scanf("%d", &val_a_tester) == 1) {
... // it's an integer
}
自制解决方案:
bool isNumeric(const char *str)
{
while(*str != '\0')
{
if(*str < '0' || *str > '9')
return false;
str++;
}
return true;
}
请注意,此解决方案不应在生产代码中使用,因为它有严重的限制。但我喜欢它来理解C-Strings 和 ASCII。
使用相当简单的代码:
int i;
int value;
int n;
char ch;
/* Skip i==0 because that will be the program name */
for (i=1; i<argc; i++) {
n = sscanf(argv[i], "%d%c", &value, &ch);
if (n != 1) {
/* sscanf didn't find a number to convert, so it wasn't a number */
}
else {
/* It was */
}
}
我为此苦苦挣扎了一段时间,所以我想我只需加两分钱:
1) 创建一个单独的函数来检查 fgets 输入是否完全由数字组成:
int integerCheck(){
char myInput[4];
fgets(myInput, sizeof(myInput), stdin);
int counter = 0;
int i;
for (i=0; myInput[i]!= '\0'; i++){
if (isalpha(myInput[i]) != 0){
counter++;
if(counter > 0){
printf("Input error: Please try again. \n ");
return main();
}
}
}
return atoi(myInput);
}
上面开始循环遍历 fgets 输入的每个单元,直到结束 NULL 值。如果遇到字母或运算符,它会将“1”添加到最初设置为 0 的 int“计数器”。一旦计数器变得大于 0,嵌套的 if 语句会指示循环打印错误消息 & 然后重新启动程序。当循环完成时,如果 int 'counter' 仍然是 0 的值,它返回最初输入的整数,用于 main 函数......
2)主要功能是:
int main(void){
unsigned int numberOne;
unsigned int numberTwo;
numberOne = integerCheck();
numberTwo = integerCheck();
return numberOne*numberTwo;
}
假设两个整数都输入正确,提供的示例将产生 int "numberOne" 乘以 int "numberTwo" 的结果。该程序将重复获得两个正确输入的整数所需的时间。
if (sscanf(command_level[2], "%f%c", &check_f, &check_c)!=1)
{
is_num=false;
}
else
{
is_num=true;
}
if(sscanf(command_level[2],"%f",&check_f) != 1)
{
is_num=false;
}
这个怎么样?
这对我有用
#include <string.h>
int isNumber(char *n) {
int i = strlen(n);
int isnum = (i>0);
while (i-- && isnum) {
if (!(n[i] >= '0' && n[i] <= '9')) {
isnum = 0;
}
}
return isnum;
}
例如:
printf("%i\n", isNumber("12")); // 1
printf("%i\n", isNumber("033")); // 1
printf("%i\n", isNumber("0")); // 1
printf("%i\n", isNumber("")); // 0
printf("%i\n", isNumber("aaa")); // 0
printf("%i\n", isNumber("\n")); // 0
printf("%i\n", isNumber("a0\n")); // 0
C 库函数 int isdigit(int c) 检查传递的字符是否为十进制数字字符。
#include <stdio.h>
#include <ctype.h>
int main () {
int var1 = 'h';
int var2 = '2';
if( isdigit(var1) ) {
printf("var1 = |%c| is a digit\n", var1 );
} else {
printf("var1 = |%c| is not a digit\n", var1 );
}
if( isdigit(var2) ) {
printf("var2 = |%c| is a digit\n", var2 );
} else {
printf("var2 = |%c| is not a digit\n", var2 );
}
return(0);
}
结果是:
var1 = |h| is not a digit
var2 = |2| is a digit
sscanf() 解决方案在代码行方面更好。我在这里的答案是一个用户构建函数,它的作用与 sscanf() 几乎相同。将转换后的数字存储在指针中并返回一个名为“val”的值。如果 val 为零,则输入格式不受支持,因此转换失败。因此,仅当 val 非零时才使用指针值。
它仅在输入为 base-10 格式时才有效。
#include <stdio.h>
#include <string.h>
int CONVERT_3(double* Amt){
char number[100];
// Input the Data
printf("\nPlease enter the amount (integer only)...");
fgets(number,sizeof(number),stdin);
// Detection-Conversion begins
int iters = strlen(number)-2;
int val = 1;
int pos;
double Amount = 0;
*Amt = 0;
for(int i = 0 ; i <= iters ; i++ ){
switch(i){
case 0:
if(number[i]=='+'){break;}
if(number[i]=='-'){val = 2; break;}
if(number[i]=='.'){val = val + 10; pos = 0; break;}
if(number[i]=='0'){Amount = 0; break;}
if(number[i]=='1'){Amount = 1; break;}
if(number[i]=='2'){Amount = 2; break;}
if(number[i]=='3'){Amount = 3; break;}
if(number[i]=='4'){Amount = 4; break;}
if(number[i]=='5'){Amount = 5; break;}
if(number[i]=='6'){Amount = 6; break;}
if(number[i]=='7'){Amount = 7; break;}
if(number[i]=='8'){Amount = 8; break;}
if(number[i]=='9'){Amount = 9; break;}
default:
switch(number[i]){
case '.':
val = val + 10;
pos = i;
break;
case '0':
Amount = (Amount)*10;
break;
case '1':
Amount = (Amount)*10 + 1;
break;
case '2':
Amount = (Amount)*10 + 2;
break;
case '3':
Amount = (Amount)*10 + 3;
break;
case '4':
Amount = (Amount)*10 + 4;
break;
case '5':
Amount = (Amount)*10 + 5;
break;
case '6':
Amount = (Amount)*10 + 6;
break;
case '7':
Amount = (Amount)*10 + 7;
break;
case '8':
Amount = (Amount)*10 + 8;
break;
case '9':
Amount = (Amount)*10 + 9;
break;
default:
val = 0;
}
}
if( (!val) | (val>20) ){val = 0; break;}// val == 0
}
if(val==1){*Amt = Amount;}
if(val==2){*Amt = 0 - Amount;}
if(val==11){
int exp = iters - pos;
long den = 1;
for( ; exp-- ; ){
den = den*10;
}
*Amt = Amount/den;
}
if(val==12){
int exp = iters - pos;
long den = 1;
for( ; exp-- ; ){
den = den*10;
}
*Amt = 0 - (Amount/den);
}
return val;
}
int main(void) {
double AM = 0;
int c = CONVERT_3(&AM);
printf("\n\n%d %lf\n",c,AM);
return(0);
}