c - 当用户输入错误的因素时,我想提供错误信息
问题描述
我想在这段代码中创建一个调试系统。
例如:我想在用户输入错误的因素时显示错误信息。
我想不出方法。如果你还是不明白,你可以看看这张照片。
这是我的猜谜游戏代码:
#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;
}
推荐阅读
- java - 对自定义 ListView 执行/添加搜索功能
- node.js - 在 javascript 中循环 - 在第一个循环完全结束之前发生回调
- javascript - 使用 React Hooks 更新和传递数据
- amazon-s3 - 使用 lambda 函数通过 s3 存储桶将巨大的 .csv 文件上传到 dynamodb 时出错
- .net - Azure Pipelines:“错误 NETSDK1004:找不到资产文件 '...\project.assets.json'。” 在使用 Cache@2 任务缓存 Nuget 包时在管道中
- python - “StatusQuerySet”对象没有属性“用户”
- javascript - laravel livewire 电线:当我插入 AdjacentHTML 时,点击不起作用
- powerpoint - 更改 pptx 语言编码
- php - preg_match_all 使用 php 的特定目录/路径
- flutter - 滚动视图在颤动中没有响应