【发布时间】:2020-08-07 21:24:17
【问题描述】:
每次我运行程序时,最后一个“if”语句都不起作用,这意味着如果我输入“no”,循环就不会中断。有人可以在这里帮助我吗?
#include <stdio.h>
int main() {
int age, i;
char ans;
for (i = 0; i < 3; i++) {
printf("\n enter your age:");
scanf("%d", &age);
if (age > 18) {
printf("your age is %d, you are allowed to enter", age);
} else if (age == 18) {
printf("I don't know what to do with you");
} else {
printf("your age is %d, you are not allowed to go in", age);
}
printf("\n continue?");
scanf(" %c", &ans);
if (ans == 'no') { // <-- here
break;
} else {
continue;
}
}
return 0;
}
【问题讨论】:
-
%c只扫描一个字符,使用if (ans == 'n') { ...或char ans[4]; scanf(" %s", ans); if (strcmp(ans, "no") == 0){ ... -
激活警告,你会得到指出的问题。
-
ans == 'no' 不起作用;正如大卫所说,使用 strcmp。
-
已经提到字符串比较不能这样工作。除此之外,
'no'不是字符串。它是一个多字符文字,它是一个具有实现定义值的整数。请改用"no"