为什么无法识别if(ch!=‘’‘&&’"')
以下为用visual studio2019编写的程序:
// chcount.c--使用逻辑与运算符
#include <stdio.h>
#define PERIOD '.'
int main(void)
{
char ch;
int charcount = 0;
printf("Enter some characters:");
while (ch = getchar() != PERIOD) {
if (ch != '\"' && ch != '\'')
charcount++;
}
printf("There are %d non-quote characters.\n", charcount);
getchar();
return 0;
}
运行后输入“I didn’t read the “I’m a Programming Fool” best seller.”
出现下面结果(此结果未识别’和"):
正确结果应该是:50
错误原因如下:
while(ch=getchar()!=PERIOD) 会先执行getchar()!=PERIOD
为真则返回1(变为ch=1) 继续执行while下面的语句 这导致ch存储的值为1 无法识别’和”
为假则返回0(变为ch=0) while循环结束
正确的应该改为 while((ch=getchar())!=PERIOD) 先给ch赋值再与PERIOD作比较