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
}