首页 > 解决方案 > 当用户输入错误的因素时,我想提供错误信息

问题描述

我想在这段代码中创建一个调试系统。

例如:我想在用户输入错误的因素时显示错误信息。

我想不出方法。如果你还是不明白,你可以看看这张照片

这是我的猜谜游戏代码:

#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;
}

标签: cfunction

解决方案


将输入读取为字符串,如果是数字,请执行您的操作。

#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;
}

推荐阅读