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