【发布时间】:2014-10-19 19:03:21
【问题描述】:
我的代码有这个问题。问题是我需要比较两个字符 n 和 a[p] 但结果总是否定的。这是我的作业的一个小测验程序。 q[] 是一组问题,a[] 是一组答案。玩家输入t 或f 判断真假,但if 似乎不起作用,因为它总是打印“你输了!” (即使条件为真)。
char questions(){
const char *q [100];
q[0]= "Centipedes always have 100 feet."; //f
q[1] = "Marie Curie’s husband was called Pierre."; //t
[...]
q[99] = "";
const char *a[100];
a[0] = "f";
a[1] = "t";
[...]
a[99] = "";
char n;
int p, i;
for (i = 0; i<=7; ++i)
{
srand(time(NULL));
p = (rand() % 18);
printf("\n");
printf(q[p]);
printf("\n");
fflush(stdin);
scanf("%c", &n);
if (n == a[p]){
printf("Correct answer!\n");
}
else
{
printf("You lose!");
break;
}
}
【问题讨论】:
-
if (n == a[p]){-->if (n == *a[p]){ -
你应该注意你的警告。
-
注意:
fflush(stdin);不从stdin中删除无关字符。您需要手动删除任何与int flush=0;类似的无关字符,然后在第二次从stdin读取之后/之前包括do { flush=getchar(); } while (flush != '\n');。这将完成您对fflush(stdin);实际未所做的事情。
标签: c if-statement comparison