【发布时间】:2014-08-12 21:23:24
【问题描述】:
我正在尝试在这里完成我的猜谜游戏,但是当用户输入正确的数字时程序会崩溃
我打算使用strcmpi 函数来评估用户的选择,但它似乎不起作用。我正在做的方式是直接使用c=getchar() 与'y' 或'n' 进行比较。不知怎的,我对此有一种不好的感觉。
因此,如果这不是正确的方法,请告诉我正确的方法是什么。
我也收到警告说
函数'strcmpi的隐式声明
在我构建它时。然后我确实尝试添加#include <string.h>,它会弹出更多错误,例如
警告:传递 'strcmpi' 的参数 1 使指针从整数而不进行强制转换 [默认启用]|
注意:预期为 'const char *' 但参数的类型为 '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()不是函数,而且这段代码甚至无法编译。也许你的意思是stricmp()?请提交一个编译的例子。另外,请阅读它,您不能将诸如“n”之类的字符常量传递给该函数-您需要传递一个字符串(例如“n”)。此外,您正在使用 getchar 读取用户输入的字符,因此您可能只喊if( c == 'n' )。 -
@JohnH -
strcmpi()和stricmp()在某些库中是同义词,尤其是 Microsoft。但正如你所说,if (c=='n')可以胜任。 -
while((c = getchar())!= '\n');是一个无限循环,应该stdin关闭。最好做int c; while((c = getchar()) != '\n' && c != EOF); -
如果第一个猜测是正确的,代码可能会失败,因为下面的
c = getchar();消耗了'\n'。 -
如果您需要可移植,另一件事是,
stricmp在 UNIX 系统上不存在...用于执行此操作的 POSIX 函数称为strcasecmp()