c - C 语言中是/否提示?

标签 c

我使用“是/否”用户提示来确定用户是否想要执行该程序或退出该程序...当您键入 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;
}

最佳答案

我希望您期望以下逻辑仅得到 yYnN 作为使用的输入来做出决定。

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/

相关文章:

c - 如何避免在 C 中将字符串作为数组循环?

更改 union 内的字节顺序或字节顺序

c - 使用 "C"执行 API 将 sqlite3 表导出到文件中

c++ - 切勿使用 ' #include "filename.h"' 指令

c - C语言中如何从文件夹中读取文件

c - GetLocalTime() API 时间分辨率

c - 从文件崩溃读取时使用 realloc 扩展缓冲区

c - 简单 C 程序中的 ASCII 字符困惑

c - 如何获得指向结构末尾的指针?

c - 列出导入的PE文件的DLL