Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confirmation before closing a C program

I'm having trouble with asking for confirmation before closing a program in C. I am looking for the program to initiate the confirm exit loop when 0 is entered however the program currently closes immediately when 0 is entered instead of asking for confirmation.

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

I am guessing I am missing a more elegant solution to this I've tried a few things and just can't get it working.

Example of what is happening: 1 is entered which adds an integer to an array integer to add is requested e.g. 8 upon pressing 0 the program is meant to state "do you wish to close, 0 for yes, any other integer for no" however when 0 is pressed the program immediately closes.

like image 291
Grubbery Avatar asked Mar 22 '26 23:03

Grubbery


2 Answers

You can include a do while loop, and include the operations in them.

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

The program will continue as long as input number is not equal to 0.

like image 64
Santhosh Pai Avatar answered Mar 25 '26 16:03

Santhosh Pai


One simple possibility is that stdin still contains a value waiting to be read (a zero specifically). Assuming that the user did not type something like 0 0 (two inputs) at the console, then it seems likely that the problem lies in the code not shown. It may somehow not be reading from stdin in quite as you expect.

like image 45
Mark Wilkins Avatar answered Mar 25 '26 17:03

Mark Wilkins