一. 引言
成功的程序总是尝试预测无效数据,并将此类数据隔离,使其不被接受和处理
首先验证数据的类型是否正确;如果没有,请要求用户重新输入数据
解释为什么输入的数据无效
验证输入数据的最常用方法之一是接受所有数字作为字符串
然后可以检查每个字符,以确保它符合所请求的数据类型
检查以下内容:
字符串不是空的。
存在有效的符号符号(+或-)
如果有一个符号符号,它后面至少有一个数字。
其余所有字符都是有效数字。
有效的数字是0到9之间的任何字符,而小于0或大于9的任何字符都不是数字
二. 代码如下:
#include <stdio.h>
#include <stdlib.h> /* needed to convert a string to an integer */
#define MAXCHARS 40
#define TRUE 1
#define FALSE 0
int isValidInt(char []); /* function prototype */
int main()
{
char value[MAXCHARS];
int number;
printf("Enter an integer: ");
gets(value);
if (isValidInt(value)== TRUE)
{
number = atoi(value);
printf("The number you entered is %d\n", number);
}
else
{
printf("The number you entered is not a valid integer.\n");
}
return 0;
}
int isValidInt(char val[])
{
int start = 0;
int i;
int valid = TRUE;
int sign = FALSE;
/* check for an empty string */
if (val[0] == '\0') valid = FALSE;
/* check for a leading sign */
if (val[0] == '-' || val[0] == '+')
{
sign = TRUE;
start = 1; /* start checking for digits after the sign */
}
/* check that there is at least one character after the sign */
if(sign == TRUE && val[1] == '\0') valid = FALSE;
/*now check the string, which we know has at least one non - sign char */
i = start;
while(valid == TRUE && val[i]!= '\0')
{
if (val[i] < '0' || val[i] > '9') /* check for a - non - digit */
{
valid = FALSE;
}
i++;
}
return valid;
}
#define TRUE 1
#define FALSE 0
#define MAXCHARS 40
int getanInt()
{
int isValidInt(char []); /* function prototype */
int isanInt = FALSE;
char value[MAXCHARS];
do
{
gets(value);
if (isValidInt(value) == FALSE)
{
printf("Invalid integer - Please re - enter: ");
continue; /* send control to the do - while expression test */
}
isanInt = TRUE;
}while (isanInt == FALSE);
return (atoi(value)); /* convert to an integer */
}
- 第一个代码主要实现了一个
isValidInt
函数来检查输入的字符串是否为有效的整数,并在main
函数中使用该函数来处理用户输入。 - 第二个代码在 Program 9.8 的基础上,进一步封装了一个
getanInt
函数,用于循环获取用户输入的有效整数,直到用户输入正确为止。
往期回顾:
C语言——海龟作图(对之前所有内容复习)_海龟图c语言-优快云博客
C语言——指针初阶(一)_c语言指针p和*p区别-优快云博客