【发布时间】:2026-01-25 14:35:01
【问题描述】:
我在 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 中执行上述所有操作?也许是一个较短的替代方案,可以确保输入是:
i) 不是一个字母 ii) 正整数或负整数
【问题讨论】:
-
把它全部放在一个可重用的函数中。将该文件包含在您的各种项目中。您也可以缩减代码,但是当显而易见的解决方案是使您拥有的内容可重用时,我懒得阅读所有内容。
-
使用标准库。
strtol做这一切。 -
@n.m.
strtol()没有正确返回错误。 -
@AlexeyFrunze:
strtol返回您需要的一切,只要正确使用即可。 -
@n.m.啊,当数字太大/太小时,我错过了关于
errno设置为ERANGE的部分。但是,当输入不是有效数字时,我不确定它是否将errno设置为某个值,您不能使用返回值 0 来区分 0 和错误。
标签: c validation input integer