Input is used to take information from the person using the program. In C++ we use a cin statement that we got from the iostream header file (It's all coming together now huh?). To connect tell a cin statement where to put the input we use the >> operator. Say we wanted to get your name (Assuming you have included the string header file and declared the name variable):


If you compiled that then you should have seen just a blinking cursor without any indication of what to do. If you entered your name the program should have just ended right there.


A blinking cursor on the screen may entertain some todlers, but we want to tell people why its there, and what the program is waiting for. The cout command is used to display text on the screen. To tell the cout statement what to display on the screen we use the << operator. The \n in a string will make the text after it go to the next line. The endl will do the same thing, but can't be in a string. The following code will display a prompt to enter your name and after you do and press enter it will display it on the screen on the next line:

string name;
cout<<"Enter your name ";
cout<<"\n Hi "<<name<<endl;

The mixing of the variables with literals (constants or strings) with variables is known as concatenation. After you entered your name it flashed that message quickly and then closed. We need to tell the system to stop at that point, and to continue when we tell it to. To achieve this we use a system function.


This will make the system display the message "Press any key to continue" and not continue until you press a key.

The say you entered your full name, the previous code would have only showed up until the first space. This is because the cin statement will only take information up to the first space. To make it take everything up until the point that you hit enter, we have to use the getline function. To implore this we need to first say getline then parenthases () and inside the parenthases we need the statement used for getting input, which could be any way to get input even a file, but for this we'll just use a cin then we seperate it with a comma and put the variable we want to store it in.

string name;
getline(cin, name);

You may run into some problems with the getline statement. I know for a fact it acts screwey when dealing with vectors, and some other things, so it may just be better to use a cin statement.

Next Section: Conditionals

Link Directory | link directory | GeekySpeaky: Submit Your Site! | Blog Matter

Copyright © 2004-2018 Sean Noble, All rights reserved
Read our Disclosure Policy