cout
you must include the following directive
at the start of your program
#include <iostream> using namespace std::cout;
cout << ...something... ;
cout << MyVariableName;
cout << "This will appear on the monitor";
cout << "\n";
int X = 17; int Y = 23; cout << "The value of variable X is " << X << "\n"; cout << "... and Y is" << Y << "\n";This would produce output
The value of variable X is 17 ... and Y is23
To include one of these as a "regular" character in an output stream, or to assign them as a character value, we have to let the compiler know that we don't want the "special" use of the character.
To do so, we use an escape sequence - which usually simply means
preceding the desired character with a backslash \
Some of the common escape sequences are listed below:
Escape sequence | Meaning |
\b | backspace |
\n | newline |
\t | tab |
\g | bell |
\\ | backslash |
\' | single quote |
\" | double quote |
\nnn | use ASCII value |
cout << "Here comes a double-quote: \" there it went ... \n";
The ASCII value for a character is an integer interpretation of the bit pattern used to store the character.
For example, the ASCII values for the characters 'A' through 'Z' are 65 through 90.
<iomanip>
library contains formatting aids
cout << "blah value " << blah << "\n"; cout << "longerblah value " << longerblah << "\n";
std::setw(x)
sets the width of the next output field,
padding with as many blanks as necessary
cout << "Boo" << std::setw(5) << "zoom\n"; cout << std::setw(6) << 3650;Pads zoom (on the left) with one space (i.e. " zoom")
Boo zoom 3650If the number is too large for the
std::setw
field it simply
ignores the std::setw
, e.g.
cout << "Boo " << std::setw(3) << 1365 << ".";produces
Boo 1365.
std::setw
works for this), and
how many decimal places of accuracy are displayed.
The latter requires a two-step process:
cout << std::setiosflags(ios::fixed); cout << std::setprecision(3) << std::setw(7) << 765.432 << "\n"; cout << std::setprecision(2) << std::setw(7) << 023.14 << "\n"; cout << std::setprecision(2) << std::setw(7) << 341.2 << "\n"; cout << std::setprecision(4) << std::setw(7) << 0.00456 << "\n";produces output
765.432 23.14 341.20 0.0046