Dear Users,
I've seen a lot of beginners asking how to prevent the command prompt from closing. Some of the answers are dangerous (i.e. system(pause)) as pointed out by more seasoned programmers. Some are much more complicated that a beginner can understand. However, I found a potential solution, but I would like the input from more experienced programmers to prevent unintended consequences.
Some have suggested using the function cin.get(), cin being an object of class istream which, when added to the end of a program, waits until the user inputs a character. This function is usually inserted immediately before "return 0" at the end of the program. However, this method does not work if you previously use the object cin somewhere else in your program to read input from the user.
I think this happens because what the user input using cin is not flushed from the buffer or stream. Therefore, when you reach the cin.get() function at the end of your program, the function already has something to "get" and it executes the function. It doesn't have to wait. Therefore, your command prompt closes immediately.
The way I circumvented this problem is to use the cin.ignore(); function immediately before the cin.get() function. The cin.ignore() function extracts and ignores characters from the input object cin. I think this cleans out the stream or buffer, and prevents the cin.get() function from executing. Then, it simply waits for a new input from the user.
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>
using namespace std;
int main ()
{
// Initialize the variables for memory storage.
int low, high;
// Ask the user for two integers and store them.
cout << "Please type two integer numbers see which numbers are between them." << endl;
cin >> low >> high;
// Use a loop to print each number between the two integers.
while (low <= high){
cout << "Count = " << low << endl;
++low;
}
// Ignores previous inputs and waits for a new input before closing.
cin.ignore();
cin.get();
return 0;
}
|
The question is: Are there unintended consequences to this approach that I don't understand yet?