是/否在C中提示?

时间:2013-02-01 19:38:41

标签: 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;
}

5 个答案:

答案 0 :(得分:2)

我希望您希望以下逻辑仅使用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');

答案 1 :(得分:1)

  

任何其他角色,不仅仅是n或N,都将停止该程序。一世   我想知道如何解决这个问题

在这种情况下,你可能想测试一下:

while(tolower(response) != 'n'));

我只能假设空的getchar()会丢掉换行符。有更好的方法可以做到这一点,但在这种情况下,您可以简单地向scanf添加一个空格:

scanf("%d ", &num);
         ^

答案 2 :(得分:1)

我认为问题在于您在程序中使用了两个getchar()

我们不知道错误。您仍然可以尝试在程序中getchar()之后立即删除printf

答案 3 :(得分:0)

另外......你可能想要替换

getchar();
response = getchar();

使用:

char c;
do{
    printf("Do you want to continue? (y/n)");
    scanf(" %c",&c); c = toUpper(c);
}while(c != 'N');

请注意(虽然没有必要),%c前面的空格是消除空格

答案 4 :(得分:0)

getchar();

替换标有fflush(stdin);的行

对我来说效果很好,这是完整的代码。

#include <stdio.h>
#include <string.h>

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");
        }

        fflush(stdin);
        printf("\n\nDo you want to try another number? Say Y(es) or N(o): ");
        response = getchar();
    } while(response == 'Y' || response == 'y');

    printf("Thank you for using my program. Good Bye!\n\n");
    return 0;
}