Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 是否限制用户输入整数?_C - Fatal编程技术网

C 是否限制用户输入整数?

C 是否限制用户输入整数?,c,C,您好,我想问一个问题,关于我如何限制用户输入整数和只输入字符串或字符 如果你知道答案,你能把它放在我下面的代码中吗?如果你能做到这一点,那就太好了。顺便说一句,忘记日期部分,这是另外一回事 void checkin() { char comp_choice,more_choice,in_comp_choice; int comp_amount; int date_month[] = {31,28,31,30,31,30,31,31,30,31,30,31}; int date_month1[]

您好,我想问一个问题,关于我如何限制用户输入整数和只输入字符串或字符

如果你知道答案,你能把它放在我下面的代码中吗?如果你能做到这一点,那就太好了。顺便说一句,忘记日期部分,这是另外一回事

void checkin()
{
char comp_choice,more_choice,in_comp_choice;
int comp_amount;
int date_month[] = {31,28,31,30,31,30,31,31,30,31,30,31};
int date_month1[] = {31,28,31,30,31,30,31,31,30,31,30,31};
int charges_per_room_per_day = 5000,bill;
struct info user;
system("cls");
printf("\t\tCHECK IN FORM\n");
printf("Please Fill Following Information\n");
FILE *fp;
fp = fopen("checkin.txt","a");
time_t t;
time(&t);
    printf("First Name : ");
    fflush(stdin);
 gets(user.first_name);
 printf("Last Name : ");
    fflush(stdin);
    gets(user.last_name);
 fflush(stdin);
printf("Contact Number : ");
gets(user.contact_no);
fflush(stdin);
printf("\nGuests : ");
scanf("%d",&user.guest);
printf("Rooms : ");
scanf("%d",&user.rooms);
fprintf(fp,"%s %s %s %d %d\n",user.first_name,user.last_name,user.contact_no,user.guest,user.rooms);
Label2:
printf("Today date and time is %s\n",ctime(&t));
printf("Check In  date (DD-MM-YYYY) : ");
scanf("%d %d %d",&user.date,&user.month,&user.year);
printf("Check out  date (DD-MM-YYYY) : ");
scanf("%d %d %d",&user.date1,&user.month1,&user.year1);

强制用户输入有效整数的一种方法是读入用户输入的任何内容(例如读入
字符[…]
-缓冲区),然后根据需要解释/检查结果。对于此检查,您可以编写自定义逻辑,或者使用内置函数的逻辑,例如,
strol

以下示例使用了
strtol
strtol
的签名是
long int strtol(const char*nptr,char**endptr,int base)
。基本上,成功扫描后,
endptr
将指向(成功)扫描编号后的
nptr
的第一个字符;如果我们不接受(有效)数字后面的任何字符,我们将检查
endptr
是否实际指向字符串终止符
'\0'
;如果扫描失败,
endptr
等于
nptr

给你:

#包括
#包括
int enterIntegerValue(常量字符*消息){
字符输入缓冲区[21];
char*endOfScan;
布尔误差;
int结果;
做{
printf(“%s”,消息);
scanf(“%20s”,输入缓冲区);
结果=(int)strtol(inputBuffer和endOfScan,10);
错误=(endOfScan==inputBuffer)| |(*endOfScan!='\0');
如果(错误)
printf(“无效数字。请输入有效整数。”);
}
while(错误);
返回结果;
}
int main()
{
int rooms=enterIntegerValue(“房间:”);
printf(“输入:%d”,房间);
返回0;
}

调用
fflush(stdin)
调用未定义的行为。
gets()
是邪恶的,用
fgets()
代替。@alikhan我已经厌倦了解释基本的所有时间。请读。我们需要定义
struct user
。没有标准的C/POSIX函数只能读取字母。您需要读取用户输入的内容,对其进行解析,然后让代码决定输入是否有效。要区分字母和数字,请看一看
是*()
函数系列(例如
isalpha()
isdigit()
,…)。