Why doesn't isdigit() work? - c

I'm trying to make a program that generates a random number, asks the user to guess and then responds whether or not he got it right. For some reason, regardless of wether the user puts in a digit or not, it responds as if he didn't. Any ideas? thanks for helping out a beginner :)
#include<stdio.h>
#include<ctype.h>
#include<time.h>
main()
{
char iRandomNum = '\0';
int iResponse = 0;
srand(time(NULL));
iRandomNum = (rand() % 10) + 1;
printf("Guess the number between 1 yand 10 : ");
scanf("%d", &iResponse);
if (isdigit(iResponse) == 0)
printf("you did not choose a number\n");
else if (iResponse == iRandomNum)
printf("you guessed correctly\n");
else
printf("you were wrong the number was %c", iRandomNum);
}

isdigit() takes the ascii value of a character and returns 0 if it's not a digit and non-0 if it is.
You are passing to it an integer value which is not necessarily an ascii value, you don't need to check if it's a digit since you read it with scanf().
If you want to make sure scanf() did read a number, check the return value of scanf() instead.
Try this
if (scanf("%d", &iResponse) != 1)
printf("you did not choose a number\n");
instead of the if (isdigit( ...
One more thing, main() must return int.

Related

Verifying inputs and repeating statements

I need to take two numbers from two separate scans and find the GCD of both of them. I have this currently which will take the two numbers, but I need to validate input with a function. It should work as follows, I enter a number and it checks to verify that it is a positive integer. If not it should prompt me to say that the input is unrecognized and ask for it again. Once I input a valid number, it should continue to ask me to put in a second one and do the same verification process. Any help with input validation and repeating the question in a function would be helpful.
int main()
{
int num1, num2, i, GCD;
printf("Please enter a positive integer: \n");
scanf("%d" ,&num1);
printf("Please enter a positive integer:\n");
scanf("%d", &num2);
if (num1 >0 && num2 > 0) {
for(i = 1; i <= num1 && i <= num2; i++)
{
if(num1 % i == 0 && num2 % i == 0)
GCD = i;
}
}
else {
printf("I'm sorry that number is unrecognized or negative.\n");
}
printf("The largest integer that divides both %d and %d is: %d\n",num1,num2, GCD);
return 0;
}
you can use a do-while loop and put your scanf in there as long as you dont get a valid answer. For example:
do {
// put your scans here
} while(num1<0 || num2<0);
Also you can catch the case if he inputs a character instead of integer input! So that is a good way to repeat a prompt until you get the valid answer.

Guessing Game in C programming

I built a guessing game in C programming using while loop, and I am having a problem with it during execution. So, when I print a number less than the guess number or greater than the guess number, I get the correct answer. But when the user enters the right answer, the screen shows the statement for the greater number "The number you entered is greater than the Secret Number." and then it shows the right statement below this "This is the secret Number." I think the problem could be because else statement does not define the condition for greater number but I am not sure how to solve this. Can somebody help me?
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Guessing game
const int SecretNum = 4;
int guess;
while (guess != SecretNum){
printf("Enter a number: ");
scanf("%d", &guess);
if (guess < SecretNum){
printf("The number you entered is less than the Secret Number. \n");
} else printf("The number you entered is greater than the Secret Number.\n");
}
printf("This is the secret number.\n");
return 0;
}
You think the problem could be because else statement does not define the condition for greater number, so you should add that.
Also you have to initialize guess before using its value.
Formatting your code using indent properly is another important portion.
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Guessing game
const int SecretNum = 4;
int guess = !SecretNum; /* initialize guess : guess will be different value from SecretNum using this */
while (guess != SecretNum){
printf("Enter a number: ");
scanf("%d", &guess);
if (guess < SecretNum){
printf("The number you entered is less than the Secret Number. \n");
} else if (guess > SecretNum) /* add condition */
printf("The number you entered is greater than the Secret Number.\n");
}
printf("This is the secret number.\n");
return 0;
}

Programming in C. Error Handling an integer value

I have an integer input for my I.D. My teacher says I need to error handle all my inputs and basically display appropriate error messages if input entered is invalid. So I'm trying to get an error message to pop up if the user enters a real number or number less than one. But what I've tried is not working!
printf("Enter client Id--->");
scanf("%d", &client.id);
while ((client.id < 1) || (client.id % 1 != 0)) {
printf("Invalid I.d entered\n");
printf("Enter client Id--->");
scanf("%d", &client.id);
} // endwhile`
scanf("%d", &client.id);
You have to test the return value of scanf. If the result is 1, it has successfully scanned your integer. All you have to do next is to test that the value is >=1.
So, something like that:
while( 1 ) {
printf("Enter client Id--->");
int scanned = scanf("%d", &client.id);
if( scanned != 1 || client.id < 1 ) {
// note: infinite loop for invalid input, see note below
printf("Invalid I.d entered\n");
}
else {
break; // OK
}
}
NB(1) see there for a an explanation of why scanf is unsafe and ways of making it safe(r).
NB(2) you haven't included the client.id declaration, but it has to be an int type. Even if you wanted to scan a float instead of an int, x % 1 != 0 is a no-no.
You can add a printf after the scanf to ensure scanf is working as expected.
Still, regardless of what value is entered, the program exits without entering while() body.
Of the two while() conditions, the first is innocuous, but the second is suspect because it is false for all values.
To check that a number is not an integer, the easiest way (the way without function calls) would be client.id != (int)client.id.
But first, you must read the number as a floating-point type, precisely so you can catch that error. My code:
double x;
printf("Enter client Id--->");
scanf("%lf", &x);
while((x < 1.0) || (x != (int)x))
{
printf("Invalid I.d entered\n");
printf("Enter client Id--->");
scanf("%lf",&x);
} // endwhile
client.id = (int)x;

Simple "Random Number Guessing Game" / IF ELSE in C not working

I have just started my Intro to Programming class (so please bear with me) and I am a bit stuck on one of the first assignments.
I am supposed to code a number guessing game to store a random number between 1 & 10 into a variable, prompt the user for a number, & notify if user guessed the same number or not.
I have been messing with it for some time now, and the code has changed quite a bit from what I started with. Currently, the program is saying "Congrats, you're a winner" no matter what I guess...
If anyone could just point me in the direction of what I am doing wrong, that would be great.
THE CODE HAS BEEN EDITED SINCE THE ORIGINAL POSTING OF QUESTION
#include <stdio.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
int main()
{
//Declare Variables
int RandomNum;
int UserGuess;
//Initialize Variables
RandomNum=0;
srand ( (unsigned)time ( NULL ) );
char UserInput = 'a';
int a = UserInput;
//Generate RandomNum
RandomNum = (rand() % 10)+1;
//Prompt User for UserInput
printf("Guess the random number!\n");
printf("Enter your guess now!\n");
scanf("%d", &UserInput);
//Determine Outcome
if (UserInput == RandomNum)
printf("You're a WINNER!\n");
else
printf("Incorrect! The number was %d\n", RandomNum);
//Stay Open
system("PAUSE");
}
Change this line -
if (UserGuess = RandomNum)
to this -
if (UserInput == RandomNum)
The first one assigns the user input stored in RandomNum into UserGuess, which is then converted to either true or false implicitly, and then the truth value of the if condition is checked by the compiler. I am assuming that you are entering non-zero value as your program input. If this is the case, then C will consider it as true. In fact, any non-zero value (whether positive, negative or fractional) is considered to be true by C.
The second expression checks for equality of two variables, rather than assigning one to another. So, you will get the desired behavior.
You are confusing = with ==
if (UserGuess = RandomNum) will not give the boolean result which you want to check that whether the guess is equal to random no generated..
Use
if (UserGuess == RandomNum)
Your if is incorrect. == is equality, = is assignment.
Change the type of UserInput, remove UserGuess and the spurious call to atoi(), and it'll work:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
//Declare Variables
int RandomNum;
int UserInput; // Changed to int
//Initialize Variables
RandomNum = 0;
UserInput = 0; // Changed initialization
srand((unsigned) time(NULL));
//Generate RandomNum
RandomNum = (rand() % 10) + 1;
//Prompt User for UserInput
printf("Guess the random number!\n");
printf("Enter your guess now!\n");
scanf("%d", &UserInput);
//Determine Outcome
if (UserInput == RandomNum)
printf("You're a WINNER!\n");
else
printf("Incorrect! The number was %d\n", RandomNum);
//Stay Open
system("PAUSE");
}
Are you sure that atoi() function takes an integer argument ?
because atoi() function is used to convert string to integer.
Read this article.

C. Printing error messages due to user entering letter instead of number

The user has to enter a number greater than 0 in order to print some stuff.
my code for when the user enters a number less than 0 uses a while loop. It then asks the user to type in a number again.
while(x<=0){
print("Must enter a number greater than 0");
printf("Enter a number: ");
scanf("%i",&x);}
How can I create an error message formatted similarly to the one above, but for a user who enters a "x" or a word. Thanks
Since the reading is done using scanf with a numeric format, it means that if you enter something that can't be read as an integer (123) or part of an integer (123x is ok, the parsing stops soon after the 3), the scanf fails (i.e. it can't parse the input as number). Scanf returns the number of successfully parsed items. So you expect 1 in your case. You can check the return value (if it's 0, scanf wasn't able to get any number from the input) but as said before you still accept thigs like 123x (and the "residual" x will be parsed in the next scanf from stdin, if you do it).
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main(void){
int x;
int ok=0;
do{
char buff[32], *endp;
long long num;
ok = !ok;//start true(OK)
printf("Enter a number: ");
fgets(buff, sizeof(buff), stdin);
x=(int)(num=strtoll(buff, &endp, 0));//0: number literal of C. 10 : decimal number.
if(*endp != '\n'){
if(*endp == '\0'){
printf("Too large!\n");
fflush(stdin);
} else {
printf("Character that can't be interpreted as a number has been entered.\n");
printf("%s", buff);
printf("%*s^\n", (int)(endp - buff), "");
}
ok = !ok;
} else if(num > INT_MAX){
printf("Too large!\n");
ok = !ok;
} else if(x<=0){
printf("Must enter a number greater than 0.\n\n");
ok = !ok;
}
}while(!ok);
printf("your input number is %d.\n", x);
return 0;
}

Resources