【问题标题】:Confirmation before closing a C program关闭 C 程序之前的确认
【发布时间】:2013-04-10 09:19:56
【问题描述】:

我在关闭 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 将整数添加到数组中 请求添加整数,例如8 按下 0 后,程序将显示“您是否希望关闭,0 表示是,任何其他整数表示否” 但是,当按下 0 时,程序会立即关闭。

【问题讨论】:

  • 您是否尝试过在if (secondinput == 0) 上设置断点并查看secondinput 的值?
  • inputsecondinput 是如何声明的?它们是什么类型的?
  • 它们都是整数。
  • 如果解决了,可以标记解决的答案,还是自己回答?

标签: c visual-studio return exit


【解决方案1】:

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

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

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

【讨论】:

  • 我会试试这个看看效果如何。
【解决方案2】:

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

【讨论】:

  • 这也是我的想法,但我尝试了不同的输入,例如1 1 1 0 它仍然关闭。我也做了一个干净的构建,但没有帮助。
  • @Grubbery:如果您可以用一个完整的示例(希望简短)来更新您的帖子,以证明该问题,那可能会导致快速解决。
  • 我已经添加了一个它应该如何工作的例子: 发生的事情的例子:输入 1 将一个整数添加到一个数组中,请求添加一个整数,例如8 按下 0 时程序表示“你想关闭吗,0 表示是,任何其他整数表示否”但是当按下 0 时程序立即关闭。
  • @Grubbery:对不起,我的意思是一个完整的 code 示例(不是您输入的内容)。
【解决方案3】:

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

#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;
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多