【发布时间】:2020-08-28 21:15:23
【问题描述】:
我想开始一个 Y 和 N Q&A 的程序。
#include <stdio.h>
#include <stdlib.h>
int main(){
char answer[256];
do {
print("\nDo you want to delete yourself of the record?\n");
scanf("%s", answer);
printf("%s", answer);
}while(answer != "Y" || answer != "N")
;
return 0;
}
如您所见,我声明了一个 char 类型的 256 个元素的变量,然后使用 scanf 我记录了用户输入并将其存储在答案中。然后,只要用户输入大写的 Y 或 N,循环就会一直询问。问题是,使用此实现,即使我输入 Y 或 N,程序也会不断询问。我应该将 char 声明更改为单个字符吗?我已经试过了:
#include <stdio.h>
#include <stdlib.h>
int main(){
char answer;
do {
print("\nDo you want to delete yourself of the record?\n");
scanf("%c", answer);
printf("%c", answer);
}while(answer != 'Y' || answer != 'N')
;
return 0;
}
但我收到了警告:
warning: format '%c' expects argument of type 'char *', but argument 2 has type int' [-Wformat=]
scanf("%c", answer);
有人对这个问题有澄清吗?
【问题讨论】:
-
answer != "Y"始终为真。answer的地址不等于"Y"的地址。 -
您无法将字符串与
==或!=进行比较。要么使用女巫字符,要么使用字符串比较函数。 -
@EugeneSh.,它们不是字符串......它们是字符
-
@JoelFan 在第一个 sn-p 中它们是字符串
-
answer != 'Y' || answer != 'N'在第二个代码中也始终为真。
标签: c do-while negation logical-or logical-and