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