我在C以下代码:Ç - 整数输入验证码
#include "stdafx.h"
#include <stdlib.h>
#include <cstring>
#include <ctype.h>
int main()
{
char buffer[20];
int num;
bool valid = true;
printf("Please enter a number\n");
fgets(buffer, sizeof(buffer), stdin);
printf("\n\n");
if(!isdigit(buffer[0])) //Checking if the first character is -
{
if(buffer[0] != '-')
{
valid = false;
}
else
{
if(!isdigit(buffer[1]))
{
valid = false;
}
}
}
char *pend = strrchr(buffer, '\n'); //Replacing the newline character with '\0'
if (pend != NULL)
{
*pend = '\0';
}
for (int i = 1; i < strlen(buffer); i++) //Checking that each character of the string is numeric
{
if (!isdigit(buffer[i]))
{
valid = false;
break;
}
}
if(valid == false)
{
printf("Invalid input!");
}
else
{
num = atoi(buffer);
printf("The number entered is %d", num);
}
getchar();
}
基本上,代码确保用户输入是正或负的整数。不允许使用字母,浮点数等。
该代码完美工作,并很好地工作。
但是,代码太长,我必须在很多程序中实现它。有没有一种简单的方法在C中执行所有上述操作?也许这确保输入是更短的替代:
ⅰ)不是字母 ⅱ)的正或负整数
把它放在一个可重用的函数中。将该文件包含在各个项目中。你可能会缩小代码,但是当显而易见的解决方案是使你可以重用时,我懒得去读它。 – evanmcdonnal 2013-03-05 20:22:07
使用标准库。 'strtol'完成了所有这些。 – 2013-03-05 20:22:39
@ n.m。 'strtol()'不会正确返回错误。 – 2013-03-05 20:24:48