Pages

Monday, February 14, 2011

Input C++

Input

cin - is just one way to allow user to interact (input) with your program via a keyboard. It is much more simplified than the scanf version of c language.

Syntax for input:

cin>>varref;

where:
    1. varref - refers to a variable that will represent the data that the user will be entering.
    2. variable - just think of it as a storage of data and it must be declared first before it can be use.
        declaring a variable:
    3. >> - is what we called the extraction operator. Where it extract data from the input (example

    Keyboard) and store it to the variable it refers.


Sample Program

#include<iostream>
using namespace std;

int main ( )
{
     string name;
     cout<<"Enter a your name: ");
     cin>>name;
     cout<<"Hello "<<name<<", welcome to programming world"<<endl;

     return 0;
}

Sample output:
    Enter you name: John
    Hello John, welcome to programming world

    1. The first line inside the main function is a declaration of variable. As discuss the variable must be declared first. Its just the same as preparing a storage for an information. The variable name is declared as string (take note that a string in c++ is not a data type but it is a class, will be discuss in advance topic, that was created to handle more than one character (string). The computer expect that the data to be stored(from the keyboard) in this variable is a string. Take note also that this method of entering string data is limited only to a single word. This is due to the restriction of cin where it consider the next word or string as another data. For example, if you entered data "John Marcelo" instead of just "john", it might affect the sequence of execution of instruction. Try to check it your self by adding a code that will ask for the age of the user and see what will happen.

    2. Again, it is usually that when try to input data, user must first have an instruction that will allow them to input what kind of data. So a cin is accompanied by cout first to display the instruction.


    4. Notice that we did not use a \n or endl to move to the next line. this is because when you type the data, for this example 6, you press the return key (enter key) at the end and thus your cursor moves to the next line.

No comments:

Post a Comment