user input character evaluation to constant character - c

I am trying to complete my guessing game here but the program would just crash when the user has input the correct number
I intended to use strcmpi function to evaluate the user's choice but it seems not working. The way that I am doing is to use c=getchar() be compared with 'y' or 'n' directly. Somehow I get a bad feeling about it.
So if this is not the proper way to do it please tell me what is the correct approach.
Also I get a warning says that
implicit declaration of function 'strcmpi
as I build it. Then I did try to add #include <string.h> and it pops out more errors indicating me that for example
warning: passing argument 1 of 'strcmpi' makes pointer from integer without a cast [enabled by default]|
note: expected 'const char *' but argument is of type 'char'
Any help would be appreciated and here is my program code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX_NUMBER 100
int main(void) {
int randNum;
srand((int)time(0));
randNum = rand() % 100 + 1;
long guessNum;
int count = 0;
do {
printf("\nplz enter a guess from integer 1 to 100: %d", randNum);
scanf("%ld", &guessNum);
if(scanf("%ld", &guessNum)==1)
{
if (guessNum < randNum && guessNum >= 1) {
printf("your guess is lower than the selected number");
count++;
printf("\nyou have %d times left to try", 100 - count);
}
if (guessNum > randNum && guessNum <= 100) {
printf("your guess is higher than the selected number");
count++;
printf("\nyou have %d times left to try", 100 - count);
}
if (guessNum < 1 || guessNum > 100) {
printf("your guess is out of the range, plz pick between 1-100");
count++;
printf("\nyou have %d times left to try", 100 - count);
}
if (guessNum == randNum) {
count++;
printf("congrats you got the right answer, you used %d times to make the right guess", count
);
printf("\nwould you like to have another round? (y/n)\n");
char c;
c = getchar();
if(strcmpi(c, 'y') == 0)
{
count = 0;
printf("plz enter an integer from 1 - 100: ");
scanf("%ld", &guessNum);
}
else if(strcmpi(c, 'n') == 0)
{
printf("the game is ended!");
break;
}else
{
printf("plz enter either y or n!");
}
}
}
else
{
printf("plz enter a valid integer from 1 - 100: \n");
char c;
while((c = getchar())!= '\n');
count++;
printf("\nyou have %d times left to try", 100 - count);
}
} while (count < MAX_NUMBER);
printf("\nthe guess time is used out!");
return 0;
}

strcmpi() operates on strings of characters, but getchar() retrieves only a single character.
You either need to do something like this:
// make a string for comparison
char s[2]={0};
s[0]=getchar();
if (strcmpi(s, "y")==0)
{
//etc
}
or this:
// compare single character
char c=0;
c=getchar();
if (c=='y')
{
// etc
}

Related

Computer try to guess user number in C

I made a programme to guess user number.
I miss something in my code, but i dont know what.
If i give input b (bigger) or s (lower), its still give me the same result.
Can you tell me please what should i add to Code to work correctly?
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char answer, input;
int untere_grenze=1, upper_limit=999, tipp=0, try1=0;
printf("\n\nThis program tries to guess a number you choose between 1 and 999\n\n");
do
{
try1=0;
do
{
//I think here is my problem
try1+=1;
tipp=untere_grenze+(upper_limit-untere_grenze)/2;
printf("\n%d. try: %d\n", try1, tipp);
upper_limit=tipp-1;
untere_grenze=tipp+1;
//I think here is my problem
do
{
printf("Please enter s (number to be guessed is smaller), b (number to be guessed is larger) or = (guess!):");
scanf(" %c", &input);
input=toupper(input);
} while (input!='S' && input!='B' && input!='=');
} while(input!='=');
printf("\n\nThe computer guessed your number in %d attempts.\n\n", try1);
do
{
printf("Do you want to run the program again (J/N)?\n\n");
scanf(" %c", &answer);
answer=toupper(answer);
} while (answer!='J' && answer!='N');
} while (answer=='J');
return 0;
}
Your code logic is horrible, recommend to rewrite, you can reference mine.
#include <stdio.h>
#include <ctype.h>
#define LOWER_BOUND 1
#define UPPER_BOUND 999
int main (void)
{
int low = LOWER_BOUND, up = UPPER_BOUND, guess, try = 0;
char input;
printf("Program will guess a number between 1 and 999,"
"please input s(smaller), b(bigger), or =(equal)\n");
while (1)
{
if (low <= up)
guess = low + (up - low) / 2;
else {
printf("Program terminate, no more guess value\n");
break;
}
++try;
retry:
printf("guess %d, please input (s/b/=)\n", guess);
scanf(" %c", &input);
if ((input = tolower(input)) == 's') {
up = guess - 1;
} else if (input == 'b')
low = guess + 1;
else if (input == '=')
break;
else
goto retry;
}
printf("Summary: Trial: %d\n", try);
return 0;
}
I don't see your program doing anything with the input.
You should guess lower or higher in the next iteration based on the input.

My for loop sequence is not ending with the perimeters are met to end

For the below code I created a RNG and ask the user to input a number from one to 20 until they guess the correct number. When they guess the correct number the printf prints the correct text so I know guesses[i] == randomNumber
I would think that the for loop would terminate since now guesses[i] != randomNumber no longer holds a true value. The loop is not terminating and continues to ask the user to guess.
Am I missing something here?
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#include <stdlib.h>
int main(void) {
time_t t;
srand(time(&t));
int randomNumber = (rand() % 19) + 1;
int guesses[30] = {0};
int i;
for (i = 0; guesses[i] != randomNumber; i++)
{
printf("Hello master, I will grant you 3 wishes if you can guess what number I have selected between 1 and 20: ");
scanf("%d", &guesses[i]);
if (guesses[i] == randomNumber) {
printf("It took you %d guesses to guess correct but I lied I cannot grant you any wishes, have a nice day. \n\n", i + 1);
}
else if(guesses[i] < randomNumber) {
printf("You guessed too low, try a higher number. \n\n");
}
else if(guesses[i] > randomNumber) {
printf("You guessed too high, try a lower number. \n\n");
}
}
return 0;
}
When the user inputs its guess, i increases by the loop increment instruction, and now your condition is applied to guess[i] which is actually the next i not the input user.
Welcome to SO..
I believe that testing the condition (guesses[i] != randomNumber) happens before advancing i (i++), so you are actually testing against i that was already advanced by 1
You can either try to use ++i instead of i++
OR
You can use a while loop instead of a for loop:
i = 0;
while (guesses[i] != randomNumber && i < 30) {
i++;
printf("Hello master, I will grant you 3 wishes if you can guess what number I have selected between 1 and 20: ");
scanf("%d", &guesses[i]);
if (guesses[i] == randomNumber) {
printf("It took you %d guesses to guess correct but I lied I cannot grant you any wishes, have a nice day. \n\n", i + 1);
}
else if(guesses[i] < randomNumber) {
printf("You guessed too low, try a higher number. \n\n");
}
else if(guesses[i] > randomNumber) {
printf("You guessed too high, try a lower number. \n\n");
}
}
Note how I also added a test for i < 30 to not get out of the array index bounds

C - What is wrong with this code, it does not continue after user entered his guess?

as you saw up there the problem is that the loop does not continue after the users has entered his code, i am wondering why this is and if you have a better purpose for me. I am new to the C language help is much appreciated!!!!!!
#include <stdlib.h>
#include <stdio.h>
int main()
{
int randomNumber = 11;
int usersGuess;
int i;
do {
printf("You need to guess a number between 0 and 20! Good Luck! \n");
for (i = 5; i > 0; i--) {
printf("You have got %d amount of tries, Guess The random number: ", i);
scanf_s("%d", usersGuess);
if (usersGuess == randomNumber) {
printf("You won");
break;
} else if (usersGuess > randomNumber) {
printf("That is wrong, random number is less than that");
} else if (usersGuess < randomNumber) {
printf("that is wrong, the random number is higher than that");
} else if (usersGuess > 20) {
printf("please guess again cause the random number is between 0 and 20");
}
}
} while(i > 0);
return 0;
}
Your code has Undefined Behaviour, which means it's buggy and anything can happen. The problem is that you're passing an integer to scanf_s where it want a pointer. Do this:
scanf_s("%d", &usersGuess);
The reason is that you want the function to write into the variable usersGuess. In C, all parameters are passed by value, so if you want an output parameter, you have to make it a pointer.

Not sure why my program keeps prompting error when I try to close it?

#include <stdio.h>
#include <stdlib.h>
int add_even(int);
int add_odd(int);
int main() {
int num, result_odd, result_even, even_count, odd_count;
char name;
printf("What is your name?\n");
scanf("%s", &name);
while (num != 0) {
printf("Enter a number:\n");
scanf("%d", &num);
if (num % 2 == 1) {
printf ("odd\n");
odd_count++;
} else
if (num == 0) {
printf("%s, the numbers you have entered are broken down as follows:\n",
name);
result_even = add_even(num);
printf("You entered %d even numbers with a total value of %d\n",
even_count, result_even);
result_odd = add_odd(num);
printf("You entered %d odd numbers with a total value of %d\n",
odd_count, result_odd);
} else {
printf("even\n");
even_count++;
}
}
return 0;
}
int add_even(int num) {
static int sum = 0;
if (num % 2 != 0) {
return 0;
}
sum += add_even(num);
return sum;
}
int add_odd(int num) {
static int sum = 0;
if (num % 2 == 0) {
return 0;
}
sum += add_odd(num);
return sum;
}
Can anyone give me some insight as to what I did wrong exactly?
The point of the code is to get inputs from the user until they decide to stop by inputting 0. Separating the evens from the odd. Tell them how many even/odd they put and the total of all the even/odd numbers.
I understand how to separate the evens from the odds. I think my issue is with my function.
There are multiple problems in your code:
scanf() causes undefined behavior when trying to store a string into a single character. Pass an array and specify a maximum length.
you should check the return value of scanf(): if scanf() fails to convert the input according to the specification, the values are unmodified, thus uninitialized, and undefined behavior ensues. In your case, if 2 or more words are typed at the prompt for the name, scanf("%d",...) fails because non numeric input is pending, no further characters are read from stdin and num is not set.
num is uninitialized in the first while (num != 0), causing undefined behavior.
functions add_even() and add_odd() are only called for num == 0, never summing anything.
functions add_even() and add_odd() should always return the sum and add the value of the argument num is it has the correct parity. They currently cause undefined behavior by calling themselves recursively indefinitely.
odd_count and even_count are uninitialized, so the counts would be indeterminate and reading their invokes undefined behavior.
In spite of all the sources of undefined behavior mentioned above, the reason your program keeps prompting without expecting an answer if probably that you type more than one word for the name. Only a single word is converted for %s, leaving the rest as input for numbers, which repeatedly fails in the loop. These failures go unnoticed as you do not verify the return value of scanf().
Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
int add_even(int);
int add_odd(int);
int main(void) {
int num, result_odd, result_even, even_count = 0, odd_count = 0;
char name[100];
printf("What is your name? ");
if (scanf("%99[^\n]", name) != 1)
return 1;
for (;;) {
printf("Enter a number: ");
if (scanf("%d", &num) != 1 || num == 0)
break;
if (num % 2 == 1) {
printf("odd\n");
odd_count++;
add_odd(num);
} else {
printf("even\n");
even_count++;
add_even(num);
}
printf("%s, the numbers you have entered are broken down as follows:\n", name);
result_even = add_even(0);
printf("You entered %d even numbers with a total value of %d\n",
even_count, result_even);
result_odd = add_odd(0);
printf("You entered %d odd numbers with a total value of %d\n",
odd_count, result_odd);
}
return 0;
}
int add_even(int num) {
static int sum = 0;
if (num % 2 == 0) {
sum += num;
}
return sum;
}
int add_odd(int num) {
static int sum = 0;
if (num % 2 != 0) {
sum += num;
}
return sum;
}
You declared:
char name; // One single letter, such as 'A', or 'M'
printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", &name); // Not enough space to store the response!
What you really want is more like
char name[31]; // Up to 30 letters, and an End-of-String marker
printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", name); // name is the location to put all those letters
// (but not more than 30!)

C random number producing garbage value

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(0));
int random = 0, guess, guesses = 1;
random = rand() % 100 + 1;
printf("The number has been generated. Input 0 to quit.\n");
do {
scanf("%d", &guess); //takes user input for guess
if (guess > random && guess != 0)
printf("Lower!\n");
else
if (guess < random && guess != 0)
printf("Higher!\n");
else
if (guess == random) {
printf("Bingo!");
return 0;
} else
if (guess == 0) {
printf("Thanks for playing, the number was %d\n", &random);
return 0;
}
guesses++;
} while (guesses != 6); //maximum of 5 guesses
printf("Thanks for playing, the number was %d\n", &random);
return 0;
}
Whenever I display the random variable when it has already generated a number a garbage value will be outputted. But the code snippet works of checking the comparison between the guess and the random number, I just can't seem to output the random number correctly.
%d in printf expects an argument of int data type. You are passing int * data type (&random).
Remove & before random in last two printfs.
printf("Thanks for playing, the number was %d\n", random);
You should pass the value of random instead of its address:
printf("Thanks for playing, the number was %d\n", random);
Note also that you should check the return value of scanf(): if you type a letter, the program will have undefined behavior, it may exit after iterating 5 times, or iterate forever or do something else entirely...
Here is an improved version:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
int random, guess, guesses;
srand(time(0));
random = rand() % 100 + 1;
printf("The number has been generated. Input 0 to quit.\n");
for (guesses = 0; guesses < 5; guesses++) {
// take user input for guess
if (scanf("%d", &guess) != 1 || guess == 0)
break;
if (guess > random) {
printf("Lower!\n");
} else
if (guess < random) {
printf("Higher!\n");
} else {
printf("Bingo!\n");
return 0;
}
}
printf("Thanks for playing, the number was %d\n", random);
return 0;
}

Resources