我正在尝试编写一个while循环,它仅在用户输入为'F'或'C'时运行。但是,我的while循环似乎不起作用。你能告诉我我的scanf和while循环条件有什么问题吗
#include <stdio.h>
#include <stdlib.h>
int main()
{
char response;
while (response == 'F' || response == 'C')
{
printf(" Please enter F or C\n");
scanf(" %c", &response);
}
return 0;
}
答案 0 :(得分:2)
response
未初始化。你的代码还没有进入scanf()
。考虑将其更改为do-while
循环。
答案 1 :(得分:0)
您必须初始化response
,试试这个
#include <stdio.h>
#include <stdlib.h>
int main()
{
char response;
response = 'F';
while (response == 'F' || response == 'C')
{
printf(" Please enter F or C\n");
scanf(" %c", &response);
}
return 0;
}
你当然可以这样做
#include <stdio.h>
#include <stdlib.h>
int main()
{
char response;
/* since you don't check for `scanf()`'s return value,
* this prevents undefined behavior
*/
response = 'F';
do {
printf(" Please enter F or C\n");
scanf(" %c", &response);
} while (response == 'F' || response == 'C');
return 0;
}
答案 2 :(得分:0)
只要response
'F'
或'C'
,您的循环就会运行。你需要的是
while (response != 'F' && response != 'C')
此外,response
未初始化。从
char response = '\0';
答案 3 :(得分:0)
在C中有两种常见的输入终止循环方式:
do {
...get input...
do_stuff();
} while (...input does not indicate exit...);
或
while (1) {
...get input...
if (...input indicates exit...) break;
do_stuff();
}
我认为后者可能更适合您的情况:
while (1) {
printf(" Please enter F or C\n");
scanf(" %c", &response);
if ('F' == response) {
do_f();
} else if ('C' == response) {
do_c();
} else {
break;
}
}