我正在尝试完成我的猜谜游戏,但当用户输入正确的数字时,程序会崩溃
我打算使用strcmpi
函数来评估用户的选择,但似乎无效。我正在做的方法是使用c=getchar()
直接与'y'
或'n'
进行比较。不知怎的,我对此感觉不好。
因此,如果这不是正确的方法,请告诉我什么是正确的方法
我也收到警告说
隐含的函数声明&#str; strcmpi
我建造它。然后我尝试添加#include <string.h>
,然后弹出更多错误,表明我是例如
警告:传递&#39; strcmpi&#39;的参数1在没有强制转换的情况下从整数生成指针[默认启用] |
注意:预期&#39; const char *&#39;但参数的类型为&#39; char&#39;
任何帮助都将不胜感激,这是我的程序代码:
#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;
}
答案 0 :(得分:1)
strcmpi()
对字符串进行操作,但getchar()
只检索单个字符。
你要么做这样的事情:
// make a string for comparison
char s[2]={0};
s[0]=getchar();
if (strcmpi(s, "y")==0)
{
//etc
}
或者这个:
// compare single character
char c=0;
c=getchar();
if (c=='y')
{
// etc
}