[英]While loop with multiple conditions in C
我正在尝试读取必须为'C'或'n'的字符。
如果不是这样,请打印错误并询问另一个字符。
#include <stdio.h>
int main(int argc, char const *argv[])
{
int c;
printf("Enter the character: ");
c = getchar();
while (!(c=='C' && c=='n')){
printf("Wrong!.\n");
printf("Enter the character: ");
c = getchar();
}
printf("\n");
return 0;
}
我得到的是:
输入字符:s
错误!
输入字符:错误!
输入字符:
就像它在while循环中检查了两次。
两件事情:
1)您正在按一个字符,然后按Enter。 那是两个字符。 如果要阅读整行,请不要使用getchar
。
2)您的条件没有道理。 c
既不等于'C'
也不等于'n'
的情况永远不会发生,因此您正在测试不可能的东西。 您的循环将永远不会结束。
getchar()
用于逐字符输入控件。 您仍然可以使用getchar()
,但必须处理键盘上的所有字符。 您可以通过忽略不需要的字符来做到这一点。
我还将重组您的循环,使其成为do-while循环,而不是while循环
要修改代码以捕获大写和小写AZ,您可以执行以下操作:
#include <stdio.h>
int main(int argc, char const *argv[])
{
int c;
printf("Enter the character: ");
do {
c = getchar();
// ignore non a-z or non A-Z
if( c < 'A' || ( c >'Z' && c < 'a' ) || c > 'z' ) {
continue;
}
// look for the characters you care about
if( c=='C' || c=='n') {
break;
}
// now we only have incorrect characters that are
// only upper or lower case
printf("%c Wrong!\n", (char)c );
printf("Enter the character: ");
} while (1);
printf("\n");
return 0;
}
尽管我还没有对此进行测试,但是您应该会得到以下信息:
输入字符:s错误!
输入字符:t错误!
输入字符:C
当您输入“ s-= + t \\ n01234C”时。
注意: “ \\ n”是我用来表示从键盘输入的回车符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.