Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random guessing game - bug

Tags:

c

I have a problem in this code when I enter a string, instead of integer. How do I check if the user has entred a character instead of integer? (I would like to put out a message to the user saying you should use numbers, not characters)

ALSO: if you find anything in this code I can improve, please help me! (I am new to C)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main () {

    int secret, answer;

    srand((unsigned)time(NULL));

    secret = rand() % 10 + 1;

    do {
        printf ("Guess a number between 1 and 10");
        scanf ("%d",&answer);
        if (secret<answer) puts ("Guess a higher value");
        else if (secret>answer) puts ("Guess a lower value");
    } while (secret!=answer);

    puts ("Congratz!");
    return 0;
}
like image 877
user1431627 Avatar asked Jul 05 '26 04:07

user1431627


1 Answers

scanf returns the number of matches is finds. In your case it will return 1 if it readss a number. 0 if it can't read a number in:

if(scanf ("%d",&answer) != 1){
    puts("Please input a number");

    // Now read in the rest of stdin and throw it away.
    char ch;
    while ((ch = getchar()) != '\n' && ch != EOF);

    // Skip to the next iteration of the do while loop
    continue;
}
like image 121
Paul Avatar answered Jul 06 '26 20:07

Paul