3

我在关闭 C 中的程序之前要求确认时遇到问题。我正在寻找程序以在输入 0 时启动确认退出循环,但是当输入 0 而不是要求确认时,程序当前立即关闭。

else if (input == 0)//if they chose to exit

        {
printf("You have input 0, program is attempting to close, do you wish to continue? Press 0 for yes, any other number for no");
scanf_s ("%d", &secondinput);


        if (secondinput == 0)
        {

            return;
        }

        else if (secondinput !=0)
        {
            print_menu(1);
            scanf_s("%d", &input);
        }

我猜我错过了一个更优雅的解决方案我已经尝试了一些东西,但无法让它工作。

正在发生的事情的示例:输入 1 将整数添加到数组中 请求添加整数,例如,按 0 时输入 8 程序旨在说明“您希望关闭吗,0 表示是,任何其他整数表示否”当按下 0 时,程序立即关闭。

4

3 回答 3

1

您可以包含一个 do while 循环,并在其中包含操作。

    do
    {
       */some operation */
       printf("\n enter an number to continue : (0 to stop) :")
       scanf("%d",&input);
     }while(input!=0);

只要输入的数字不等于 0,程序就会继续。

于 2013-04-17T14:47:30.753 回答
1

一种简单的可能性是标准输入仍然包含一个等待读取的值(特别是零)。假设用户没有0 0在控制台上键入(两个输入)之类的东西,那么问题很可能出在未显示的代码上。它可能不会像您期望的那样从标准输入中读取。

于 2013-04-17T14:48:12.387 回答
1

我不确定你的代码的其余部分是什么样的,但是当我输入 1 和 0 时,我能够让这段代码完美地工作,(我正在使用 Visual Studio 2008 和 Visual C++)

#include <stdio.h>

int main(int arg, char** args)
{
    int input;
    int secondinput;

    while(1)
    { 
        printf("input: ");
        scanf_s("%d", &input);
        if (input == 1)
        {
            //dosomething
        }
        else if (input == 0)//if they chose to exit

        {
            printf("You have input 0, program is attempting to close, do you wish to continue? Press 0 for yes, any other number for no");
            scanf_s ("%d", &secondinput);


            if (secondinput == 0)
            {

                return 0;
            }
        }
    }
}
于 2013-04-17T15:10:12.473 回答