Okay then lets back track a little. As you know cout tells the computer to output something such as a string or varaiable and we have already seen it used in our "Hello World " program like so:
Code:
#include <iostream>
using namespace std;
int main()
{
cout<<"Hello World! "<<endl;
cin.get();
return 0;
}
cout stands for console output, but does console
input exist? Yes this is called a cin statment and like cout it is contained within the iostream header file. In order to use the cin statment in our program we go like this:
Code:
#include <iostream>
using namespace std;
int main()
{
int userAge;//Here we declare a integer variable named userAge.
cout<<"Hello World!"<<endl;
cout<<"How old are you?"<<endl;
cin>>userAge;//Here we use a cin statment for user input. Notice how we use two greter than signs rather than two less than signs. You will learn about this later.
cin.get();
return 0;
}
Now here is the problem with using cin.get() that I forgot to mention. When you press enter for your cin statment you then tell the computer to save whatever you typed into the integer userAge. However when you press "enter" it actually stays in the keyboard buffer rendering cin.get() useless for pausing. So what you do is add another dirivative of cin known as cin.ignore(); which will ignore the last key you typed(enter) thus pausing the program.
In the end we should have this:
Code:
#include <iostream>
using namespace std;
int main()
{
int userAge;//Here we declare a integer variable named userAge.
cout<<"Hello World!"<<endl;
cout<<"How old are you?"<<endl;
cin>>userAge;//Here we use a cin statment for user input. Notice how we use two greter than signs rather than two less than signs. You will learn about this later.
cout<<"Wow you are "<< userAge <<" year(s) old."<<endl;
cin.ignore();//Ignores the last key typed being enter.
cin.get();
return 0;
}
Now in order to tell the user to press the enter key again all you have to do is add a cout statment below cin.ignore saying "Press enter to continue."
Now cin is very interesting. If you enter a number it will treat it s one, if you enter a string it will treat it as a string. Yet what if we want only one single character. This is when we use cin.get() such as in the program in my last post. The difference between cin.get() and cin is basically when you enter somthing it will treat what you typed as an appropiate data type while cin.get() will treat everything as a char value and will even cut off what you typed into a single char.
Does that make more sense? Again I can give you an example.
Edit: I just noticed but my posts are really long. Sorry about that.