Program exits immediately - alternatives to system pause?

I'm very new to C++
and I've only written 2 programs in it so far

the "Hello world" program
and a program that takes the square root of a number that you type in

My Hello World program would exit immediately after it printed "hello world" but after googling it I found two possible solutions:

the system pause (supposedly is a bad habit! and I really don't want to develop bad habits)

or this:
 
cin.ignore( numeric_limits<streamsize>::max(), '\n' );


Unfortunately, in the second program, this doesn't work -

it STILL exits immediately.

Here is the code for both my "helloworld" program
and my "sqrt" program

Hello world!

1
2
3
4
5
6
7
8
9
10
11
12
13
//Hello World in C++
//December 11, 2011 

#include <iostream>
#include <limits> 
using namespace std;

int main ()
{
  cout << "Hello World! ";
  cin.ignore( numeric_limits<streamsize>::max(), '\n' );
  return 0;
}


Sqrt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//Square Root program 
//C++ program #2 
//December 11, 2011

#include <iostream> 
#include <limits>
#include <cmath> 
using namespace std; 

int main ()
{
    float x; 
    float square; 
    cout << "Enter a number to take the square root of: ";
    cin >> x; 
    square = sqrt(x); 
    cout << "The square root of X is: ";
    cout << square; 
    cout << "Press the enter key to exit. ";
    cin.ignore( numeric_limits<streamsize>::max(), '\n' );
    return 0; 
}


Why isn't this working?
If I use the system pause, it works, but I don't want to as I want to get into good programming habits rather than bad ones (as there's no point in practicing programming with things I won't end up using)
Apparently "cin.get()" is supposed to work too, I tried that for the sqrt program but it isn't either

Is there some flaw in the code or something?

Thanks
Because after reading x: cin >> x; there is a newline character in input stream ()after entering x you should press Enter). And cin.ignore( numeric_limits<streamsize>::max(), '\n' ); just discards it without waiting for your input.
Try to double this code:
1
2
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
Thanks, it works now!

:)

Oh and I have another question:

for each cin >>
I have in the program
Do I have to add more and more of this code at the end?:
 
cin.ignore( numeric_limits<streamsize>::max(), '\n' );


Like if there's two times in the program where there's cin >>
would there have to be three of that code at the end?
Last edited on
Two will be enough.
tried it with a program using more than two and it works!

thanks for the help! :)





Topic archived. No new replies allowed.