gpt4 book ai didi

c - 用户输入字符评估为常数字符

转载 作者:行者123 更新时间:2023-11-30 15:30:54 27 4
gpt4 key购买 nike

我试图在这里完成我的猜谜游戏,但是当用户输入正确的数字时程序就会崩溃
我打算使用strcmpi函数来评估用户的选择,但它似乎不起作用。我正在做的方式是使用 c=getchar()'y' 进行比较或'n'直接地。不知怎的,我有一种不好的预感。
因此,如果这不是正确的方法,请告诉我正确的方法是什么。
我还收到一条警告说

implicit declaration of function 'strcmpi

当我构建它时。然后我尝试添加 #include <string.h>它会弹出更多错误,表明我例如

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'

任何帮助将不胜感激,这是我的程序代码:

#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() 对字符串进行操作,但 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
}

关于c - 用户输入字符评估为常数字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25274284/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com