如何解决当用户输入错误的因素时,我要显示错误信息
我想用这段代码创建一个调试系统。
例如:我想在用户输入错误因素时显示错误信息。
我不知道一种方法。如果还是不明白,可以take a look at this photo。
这是我猜的游戏代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void guessing();
int main()
{
char option;
do{
guessing();
printf("Do you want to continue(y/n): \n");
scanf(" %c",&option);
}while(option=='y'); //when while set up,carry out "do".
return 0;
}
void guessing(){ //guessing function
srand(time(0)); //different number to make.
int answer = rand() % 100; //range at 0~99
int guess;
do
{
printf("pls enter your number to guess(0~99): ");
scanf("%d",&guess);
if (guess > answer)
{
printf("smaller.\n");
}
else if (guess < answer)
{
printf("bigger\n");
}
else if (guess == answer)
{
printf("got it! The answer is %d\n",answer);
}
}while (guess != answer);
return;
}
解决方法
将输入读取为字符串,如果输入为数字,请执行操作。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
void guessing();
int main()
{
char option;
do{
guessing();
printf("Do you want to continue(y/n): \n");
scanf(" %c",&option);
}while(option=='y'); //when while set up,carry out "do".
return 0;
}
void guessing(){ //guessing function
srand(time(0)); //different number to make.
int answer = rand() % 100; //range at 0~99
int guess;
char in[32] = {0};
int i=0;
char isNumber = 0;
do
{
isNumber = 1;
printf("pls enter your number to guess(0~99): ");
scanf("%s",in);
for(i=0;i<strlen(in);i++) {
if(!isdigit(in[i])) {
printf("Error in input\n");
isNumber = 0;
break;
}
}
if(!isNumber)
continue;
guess = atoi(in);
if (guess > answer)
{
printf("smaller.\n");
}
else if (guess < answer)
{
printf("bigger\n");
}
else if (guess == answer)
{
printf("got it! The answer is %d\n",answer);
}
}while (guess != answer);
return;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。