I am currently taking a Programming Fundamentals college class that deals with the C programming language. One assignment that I have is to make a program that creates a random number from 1 to 10, and has the user guess the number. The problem I am having is that I have to use the isdigit() function to check that the guess is a number. I have used
scanf("%c", &userChar);
to store the argument to check that the guess is a digit in the following manner:
if isdigit(userChar)
However, I want to check to make sure that the number is between 1 and 10 by converting ‘userChar’ to an int variable to check in the following manner:
if (userNum >= 1 && userNum <= 10)
I have not yet learned how to do this so I was hoping someone from this site could help me. Also, I need it to check whether or not the user guessed the right number. Thanks in advance.
Since 10 cannot be stored in a single character, you would either need to use two digits, or to ask the user to guess a number from 0 to 9, inclusive.
To make an
intfrom a single-digit character use this code snippet:This works, because digits 0 through 9 are located next to each other in the ASCII encoding: the code for
1equals the code for0plus one; the code for2equals the code for0plus two, and so on. Therefore, when you subtract the code of0(which is denoted as'0'in C) from a single-digit character, you get the integer value of the corresponding digit.