Introduction to C / C++ Programming
Input and Output
Basic Input and Output
- The most common input and output commands are:
- cout << "Quoted strings and " << variables;
- cin >> variable;
The 3 Standard I/O Streams
- cin - Standard input, normally the keyboard.
- cout - Standard output, normally the screen.
- Only the RESULTS of the program ( useful work product ) should be sent to cout.
- cerr - Standard error, also normally the screen.
- Error messages should be sent to cerr instead of cout.
- Other messages, such as "Please enter X " should also really be sent to cerr, so that they can be separated from the results.
- Data sent to cout is buffered, and may not be written until the buffer is full or flushed ( e.g. with endl ), whereas any data sent to cerr is transmitted immediately.
- cout.setf( format flags );
- ios::showpoint - Show the decimal point, even for integral numbers
- ios::fixed - Fixed notation, opposite of scientific notation. Also holds number of displayed digits to a fixed amount ( in conjunction with setprecision ) even if trailing zeros must be kept.
- ios::scientific - Scientific notation, e.g. 6.02E23
- ios::right - Right justified
- ios::left - Left justified
- manipulators added to the output stream
- Must #include <iomanip> to use these manipulators
- Fed into the output stream along with data to be printed.
- Example: cout << "X = " << fixed << setprecision( 2 ) << X << endl;
- showpoint - Forces the decimal point to be shown, even if there are no fractions, e.g. 3.0 instead of 3
- fixed - Opposite of scientific notation. Also holds number of displayed digits to a fixed amount ( in conjunction with setprecision ) even if trailing zeros must be kept.
- scientific - Scientific notation, i.e. 6.02E23
- setprecision( n ) - Set the number of digits after the decimal point, e.g. 2 for money
- setw( n ) - Set the total width of the field used to hold the number.
- right - Right justified
- left - Left justified
- Note that setf( format flags ) sets the condition of the output stream permanently ( until changed with another setf( ) or an unsetf( ) command ), whereas the manipulators only affect the next value to be output. Unfortunately there are not setf( ) equivalents for all the manipulators, e.g. setw( n ).