我在关闭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时,程序立即关闭。
答案 0 :(得分:1)
您可以包含do while循环,并在其中包含操作。
do
{
*/some operation */
printf("\n enter an number to continue : (0 to stop) :")
scanf("%d",&input);
}while(input!=0);
只要输入数字不等于0,程序就会继续。
答案 1 :(得分:1)
一个简单的可能性是stdin仍然包含一个等待读取的值(具体为零)。假设用户没有在控制台上键入类似0 0
(两个输入)的内容,那么问题可能在于未显示的代码。它可能不会像你期望的那样从stdin读取。
答案 2 :(得分:1)
我不确定你的代码的其余部分是什么样的,但是当我输入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;
}
}
}
}