AltaVista Find this:  

Input/Output: cin/cout

cin and cout are used to perform input and output operations.

The syntax for the cin/cout statements are:

cin >> var1 >> var2 >> ... >> varN;

cout << expr1 << expr2 << ... << exprN;

var1 to varN are the variables that will be assigned the values read by cin. Each value must be separated by either a space, tab, or newline. If there are less values entered than expected, the remaining variables will be assigned a NULL value. Conversely, if there are more values entered than expected, the excess values will not be accepted.

expr1 to exprN are the expressions to be output by cout. The expressions can consist of variables or functions.

To insert a carriage return (ie. a line break), endl or "\n" can be used, as in:

// Assume variable 'name' has a value of 'Lisa'

cout << "My name is " << name << "." << endl;


cout << "My name is " << name << ".\n";

Both of the above lines will be printed out as:

My name is Lisa.



If you want to print an integer variable out as a character, you can cast it; that is, you can instruct the C++ compiler to convert the existing variable to be of another type. For example:

int i;

char c;

cout << "Please enter an integer value for i: ";

cin >> i; // assume '65' was entered

cout << "Please enter a character value for c: ";

cin >> c; // assume 'A' was entered

cout << "The value of 'i' is " << i << ".\n";

cout << "The character equivalent of 'i' is " << (char) i << ".\n\n";

cout << "The value of 'c' is " << c << ".\n";

cout << "The integer equivalent of 'c' is " << (int) c << ".\n";

The above will be printed out as:

The value of 'i' is 65.

The character equivalent of 'i' is A.

The value of 'c' is A.

The integer equivalent of 'c' is 65.

Casting a variable leaves the original variable unchanged.

Casting is only successful if the variable can be represented in the target format (e.g. an integer can not be casted into a structure type)

Why does 'A' translate to the value 65? Because the system we are running on uses the ASCII character set, a code for representing alphanumeric information. The upper-case alphabet, for example, begins at value 65 ('A') and ends at value 90 ('Z'); its lower-case counterpart begins at value 97 ('a') and ends at value 122 ('z'). As an exercise, write a program that will print out the entire ASCII character set, displaying an ASCII value along with its alphanumeric equivalent. There are 255 characters in the ASCII character set.


int i, j, k, l, m;

cout << "Please enter five integers separated by a space: ";

cin >> i >> j >> k >> l >> m;

// Assume entered values were: 54 23 456 1 88

cout << "The first value is: " << i << endl; // 54

cout << "The second value is: " << j << endl; // 23

cout << "The third value is: " << k << endl; // 456

cout << "The fourth value is: " << l << endl; // 1

cout << "The fifth value is: " << m << endl; // 88

Win Cash & Cool Prizes!!!!! Click to win $10,000 Cash

Back to Programming Section