我在 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();
}
基本上,代码确保用户输入是正整数或负整数。不允许使用字母、 float 等。
代码运行完美并且很好地完成了它的工作。
但是,代码太长,我必须在多个程序中实现它。有没有一种简单的方法可以在 C 中执行上述所有操作?也许有一个更短的替代方案可以确保输入:
i) 不是一个字母 ii) 正数或负数
最佳答案
bool valid = false;
char *c = buffer;
if(*c == '-'){
++c;
}
do {
valid = true;
if(!isdigit(*c)){
valid = false;
break;
}
++c;
} while(*c != '\0' && *c != '\n');
注意:这不会处理十六进制值,但会传递八进制(从 0 开始的整数)
我还必须同意,这应该放在一个公共(public)库中并作为函数调用。
关于C - 整数输入验证代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15233268/