我使用“是/否”用户提示来确定用户是否想要执行该程序或退出该程序...当您键入 y 或 Y 时,它将再次执行该程序。但是,任何其他字符(不仅仅是 n 或 N)都将终止该程序。我想知道如何解决这个问题?
int main() {
unsigned num;
char response;
do {
printf("Please enter a positive integer greater than 1 and less than 2000: ");
scanf("%d", & num);
if(num > 1 && num < 2000) {
printf("All the prime factors of %d are given below: \n", num);
printPrimeFactors(num);
printf("\n\nThe distinct prime factors of %d are given below: \n", num);
printDistinctPrimeFactors(num);
} else {
printf("Sorry that number does not fall within the given range.\n");
}
printf("\n\nDo you want to try another number? Say Y(es) or N(o): ");
getchar();
response = getchar();
}
while (response == 'Y' || response == 'y'); // if response is Y or y then program runs again
printf("Thank you for using my program. Good Bye!\n\n"); //if not Y or y, program terminates
return 0;
}
最佳答案
我希望您期望以下逻辑仅得到 y
、Y
、n
或 N
作为使用的输入来做出决定。
do
{
...
r = getchar();
if (r == '\n') r = getchar();
while(r != 'n' && r != 'N' && r != 'y` && r != `Y`)
{
printf("\invalid input, enter the choice(y/Y/n/N) again : ");
r = getchar();
if (r == '\n') r = getchar();
}
}while(r == 'Y' || r == 'y');
关于c - C 语言中是/否提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14653749/