gpt4 book ai didi

c++ - 阅读和检查字符问题

转载 作者:太空宇宙 更新时间:2023-11-04 12:27:26 26 4
gpt4 key购买 nike

这是我的代码

#include<stdio.h>

int main()
{

char choice;

printf("Do you want to enter a number:");
scanf("%c",&choice);

while(choice == 'y')
{
printf("Entered number\n");
printf("Do you want to enter a number:");
scanf("%c",&choice);


}

printf("End\n");

return 0;
}

输出是

Do you want to enter a number:y
Entered number
Do you want to enter a number:End

第一次,它检查我的字符是否是'y',但在第一次执行后的循环中,它不等待用户输入,它只是终止循环。可能出了什么问题?请帮忙

最佳答案

看看 - http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1044873249&id=1043284392

#include<stdio.h>

int main()
{
char choice;

printf("Do you want to enter a number:");
scanf("%c",&choice);

while (choice == 'y')
{
while ((choice = getchar()) != '\n' && choice != EOF);
printf("Entered number\n");
printf("Do you want to enter a number:");
scanf("%c",&choice);
}

printf("End\n");

return 0;
}

请勿使用:fflush Why fflush(stdin) is wrong

关于c++ - 阅读和检查字符问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1413998/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com