Wednesday, May 5, 2010

Basic I/O

All intro courses in programming begin with a "Hello World" program [except those that don't -- Ed], and so does this one.
#include
int main(void)
{
cout << "Hello EDM/2" << endl;
return 0;
}
Line 1 includes the header , which is needed for the input/output operations. In C++ writing something on standard output is done by:
cout << whatever;
Here "whatever" can be anything that is printable; a string literal as "Hello EDM/2", a variable, an expression. If you want to print several things, you can do so at the same time with:
cout << expr1 << expr2 << expr3 << ...;
Again, expr1, expr2 and expr3 represents things that are printable.
In the "Hello EDM/2" program above, the last expression printed is "endl" which is a special expression (called a manipulator. Manipulators, and details about I/O, will be covered in a complete part sometime this fall) which moves the cursor to the next line. It's legal to cascade more expressions to print after "endl," and doing so means those values will be printed on the next line.
As usual, string escapes can be used when printing:
cout << "\"\t-\\\"\t" << endl;
gives the result:
" -\" "
The spaces in the printed result are tabs (\t.)
Reading values from standard input is done with:
cin >> lvalue;
Here "lvalue" must be something that can be assigned a value, for example a variable. Just as with printing, several things can be read at the same time by cascading the reads:

No comments:

Post a Comment