Delaying the exit

Hi, my application is supposed to display the message and end when the condition is met. The problem is that it exits so quickly that the user is not able to view the message even though it is displayed. For seconds I even tried milliseconds but still the application doesn't delay the exit.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream> // for using cout
#include <stdlib.h> // for using exit and sleep function

using namespace std; // for using cout without having to write std::cout each time u use cout

int main()
{
    for (int x; x<1000000000;) {
        cout << "Enter a number other than 5"<< endl;
        cin >> x;
        if ( x==5 ) {
            cout << "Hey! You were not suppose to enter enter 5.";
            sleep (60000000); // make program waiting for 1 minute 60000000 microseconds=60seconds
            exit (0);
        }
    }
    return 0;
}
/* the for loop asks the user to enter numbers less than 1000000000, if any number that is >= 1000000000 is entered the program is terminated (return 0 does this part).
the value of x within the for loop is meaningless as even if u enter 6 nothing would happen. By the way you don't even need the increment as it does not affect the program.
It is important to have the nested if statement in the for loop so that the program can detect when the user enters the number 5, and cout the message listed above. It is very
important to have an exit statement within the if statement curly braces so that the program is terminated when the condition is met. But in order for the exit statement to work
we need the header <stdlib.h> else the exit function won't work and even the program itself won't run. */
Last edited on
Do not forget to initialize x to a value that is less than 1000000000. Some compilers write code that implicitly initializes integral types to zero, but only when you are in so-called "debug" mode. Do not rely on it, as they are not required to (and will not if you turn on any optimization at all). As it stands now, your program is exhibiting "undefined behavior", which means that anything at all can happen to your computer or your program if you run the code.
In practice, `x' will contain whatever was on the stack at it's address. Garbage.

That's not your problem, but also

On many platforms (x86_64 and ix86), a variable of type int is only 4 bytes wide. This means that there are 31 bits of mantissa and one sign bit, giving a range of a bit over 2147 million (exactly 2^31 - 1) to (- (2^31), inclusive.

That's not much bigger than 1000000000.

Now to answer your question:

There is a sticky post named "console closing down" on the top of the board that addresses your very problem. You are expected to do some research before asking for other's time.

The short answer is that you shouldn't do anything to stop the console window from closing before you can read the output, but you should instead run the command line program from the command line.

You should try and keep your console programs non-interactive. This is the point of console programs. If you have to have them ask for input interactively, you are only hampering their usability from a scripting standpoint.

The long answer (or, the one you want) is that you can add a thing like this to the top of your code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# include <iostream>
# include <limits>
namespace {
    using std:: cin;
    using std:: numeric_limits;
    struct KeepAlive {
      ~ KeepAlive () {
        if (! cin) {
          cin.clear  ();
        }

        cin.ignore (numeric_limits <std:: streamsize>:: max (), '\n');
        cin.get    ();
      }
    } pause_at_exit;
}


Also, in C++ no standard header files end with an `.h'. The ones inherited from C should be named with a `c' in front, e.g., #include <stdlib.h> should be #include <cstdlib> instead.

P.S.: Since C++11, there is a standard way to sleep. There is no sleep function in <cstdlib>, nor <stdlib.h>. The one you are using doesn't exist everywhere because it is non-standard. For instance, my system's sleep function is in a system library <unistd.h> (and the semantics are different), but now that doesn't matter at all, because you can (and should) instead write

1
2
3
# include <thread>
# include <chrono>
std:: this_thread:: sleep_for (std:: chrono:: minutes (1));

Last edited on
As it stands now, your program is exhibiting "undefined behavior", which means that anything at all can happen to your computer or your program if you run the code.


I don't get what you mean by that can you explain this part in simple words. What exactly could happen to my computer by running this code? I am new to c++. And i didn't get the memory part of the chapter, even though I have read and tried to understand it 3 times already.
And FYI I did research before asking here. I tried everything mentioned for headers and other functions for exiting but just doesn't seem to be working for me. The only thing I didn't try is the one last one that u posted as I just came across it. If you can't talk politely then please don't try to help if you have to show that much attitude and try to intimidate the beginners go somewhere else. We have honor. As beginners we don't get things so easily and c++ is a very difficult language, but since I love it I am investing my time and energy to understand it.
> What exactly could happen to my computer by running this code?

The C++ standard does not say what should happen if we run a program that engenders undefined behavior

undefined behavior- there are no restrictions on the behavior of the program. ...
Compilers are not required to diagnose undefined behavior (although many simple situations are diagnosed), and the compiled program is not required to do anything meaningful.
...
Because correct C++ programs are free of undefined behavior, compilers may produce unexpected results when a program that actually has UB is compiled with optimization enabled:
http://en.cppreference.com/w/cpp/language/ub
Last edited on
By the way I just tried what u have just suggested at the end, it displays an error message saying u might have to compile it manually and it doesn't even exist in this library so might have to get a library for it too and so on.
I am using Code::blocks GNU GCC compiler things are different.
Last edited on
The only thing I can think of that might have offended you in my post is this:

There is a sticky post named "console closing down" on the top of the board that addresses your very problem. You are expected to do some research before asking for other's time.

Both of those sentences are true statements that don't pass judgement against you. There is a sticky post on the top of the board that addresses your problem, and you are expected to try to find a solution on your own before asking other people. Since you posted the same question but didn't reference what you didn't understand elsewhere or any other place you have tried to find an answer, I feel like it was a fair assumption that you didn't try at all. If I was mistaken, I apologize.

Remember that we're talking about a subject for which correctness is extremely important. That's why my writing style is the way it is, so please don't mistake it for hostility. Also, you're not your program! Critiques of your program aren't critiques of you, so please don't take them that way.

All the code I have posted here is standard. That means that it will compile under any standards-compliant compiler. GCC is compatible; I compiled and tested the code I posted with both GCC (G++ v6.1.1) and Clang (v3.8.1).

The standard library headers <thread> and <chrono> were introduced in C++11. That means that you cannot use the "sleep" line unless you compile your code using a C++11 (or later) compiler. Depending on the version of GCC used in the back-end (<G++ 5.1+?) you may have to pass the option --std=c++11 on the compiler command line.

If adding a compiler flag doesn't fix it, there's something else wrong. You should post your entire error message and the code so that we can help to diagnose. If you have copied and pasted, maybe I've made a typo.
closed account (48T7M4Gy)
The problem is that it exits so quickly that the user is not able to view the message even though it is displayed.


Unless you want to something 'special' this is an age old problem, especially if you are using Visual Studio. It is easy to get around without resorting to time delays or any other artifacts and encumbrances.

If you are using VS, what you do is find/search for the .exe file in the Debug or Release folder of the particular project and open up the program in that directory. Run the program by typing xyz (the name of the exe file) and everything unfolds.

The terminal will stay open as long as you want and then it can be used as you update and recompile. ie don't close the terminal if you are still planning on debugging.
Last edited on
Topic archived. No new replies allowed.