c - 使用字符输入执行 while 循环

标签 c char do-while

我编写了这个简单的程序,它应该计算用户输入的数字的阶乘。程序应要求用户停止或继续程序,以便找到新数字的阶乘。

由于大多数时候用户不注意 CapsLock,程序应该接受 Y 或 y 作为"is"的答案。但是每次我运行这个程序时,即使我输入 Y/y ,它也会被终止!

我用谷歌搜索,发现问题可能是由于我的字符输入接受了换行字符,因此,我修改了 scanf("%c", &choice) 中的 scanf 代码;scanf("%c ", &choice); 以适应换行符,但我的程序在接受 Y/y 作为输入后仍然被终止。

这是代码。如果可能的话,请让我知道处理此类问题的最佳实践和方法以及所需的纠正。

#include<stdio.h>
#include"Disablewarning.h" // header file to disable s_secure warning in visual studio contains #pragma warning (disable : 4996) 

void main() {
    int factorial=1;//Stores the factorial value
    int i; //Counter
    char choice;//stores user choice to continue or terminte the program

        do {//Makes sure the loop isn't terminated until the user decides
            do{
                printf("Enter the no whose factorial you want to calculate:\t");
                scanf("%d", &i);
            } while (i<0);

        if (i == 0) //calculates 0!
            factorial = 1;
        else {//Calculates factorial for No greater than 1;
            while (i > 0) {
                factorial = factorial*i;
                i--;
            }
        }

        printf("\nThe factorialof entered no is :\t%d", factorial);//prints the final result

        printf("\nDo you want to continue (Y/N)?");
        scanf("%c ", &choice);

    } while (choice =="y" || choice =="Y"); // Checks if user wants to continue 

}

我是编程初学者,我在 Visual Studio 2015 中运行此代码。

最佳答案

只需修改你的 scanf 如下:

printf("\nDo you want to continue (Y/N)? ");
scanf(" %c", &choice); //You should add the space before %c, not after

您还应该使用:

} while (choice == 'y' || choice == 'Y'); // Checks if user wants to continue

注意: 单引号 ' 用于字符,双引号 " 用于字符串

关于c - 使用字符输入执行 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40585304/

相关文章:

c - SDL_QUIT 事件适用于 g++ 但不适用于 gcc

c - 有没有办法将 void *buf 转换为 char?

无法将字符串分配给 C 中的扑克牌程序的单个字符变量

c++ - 拆分并从字符串转换为字符数组

bash - 如何从 bash 中的文件循环打印 2 列

c - 以二进制形式打印文件(1 和 0)

c - LCD 遵循命令但不显示字符

c - Malloc 返回 null

Python 在达到某个点时停止迭代

JAVA:嵌套的 do-while 循环如何丢弃输入缓冲区中的字符?