C++ Input and Output Operators: >> and <<, Manipulators, and Examples - Prof. Sandra Huert, Study notes of Computer Science

The extraction operator '>>' and insertion operator '<<' in c++ for input and output of different data types, including integers, doubles, and strings. It also covers various manipulators and their uses for formatting output. An example program demonstrating the usage of these operators and manipulators is provided.

Typology: Study notes

Pre 2010

Uploaded on 03/28/2010

koofers-user-85n
koofers-user-85n 🇺🇸

10 documents

1 / 9

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
C++ INTERACTIVE INPUT AND OUTPUT
Input
The extraction operator >> is used for general input of variable values.
The extraction operator is defined for all the built-in basic C++ types. It
is possible to input values for multiple variables in the same statement by
chaining them together with the extraction operator. For each occurrence
of >> you must supply the name of the variable where you want the input
value assigned (a statement can’t end with >>).
cin >> value1 >> value2; is the same as cin >> value1;
cin >> value2;
Rules for how C++ reads different types of values:
int Skip any leading spaces or blank lines, read digits until encountering a
character that is not valid in an integer value, like a blank space or a
special character, or a decimal point, or a letter, or the end of the line
(result of pressing Enter)
double Skip any leading spaces or blank lines, read digits until encountering a
character that is not valid in a floating-point value, like a blank space
or a special character other than a decimal point, or a letter, or the end
of the line.
char Skip any leading spaces or blank lines and read the first non-blank
character encountered.
string Skip any leading spaces or blank lines and read characters
until encountering a blank space or the end of the line.
When you’re reading from the keyboard, you should precede your input
statements with output statements explaining what it is that your program
is expecting the user of the program to enter – these are called prompting
messages. Otherwise, the cursor will be blinking on the output screen, but
the user of the program has no way of knowing what the program is waiting
for.
Prompting messages should be brief because people tend not to read instructions
very well. Sometimes it helps to give the user an example of the input the
program expects rather than to try and write out a long detailed description.
Some knowledge about the anticipated users of your program may give you
an idea of the amount of detail that would be necessary or desirable in your
instructions.
You can input the values your program needs in any order you want and in
any combination you want (one at a time, two at a time, etc.). I strongly
recommend reading only one value at a time because it greatly simplifies
the instructions and possibly helps to prevent errors by the user while keying
the input values. If you expect the user to enter multiple values without
additional instructions in between values, then you probably need to explain
about the spacing required. If you’re only asking for one value at a time,
spacing isn’t a problem.
// Monty Python
// Program 1
// CSCI 151 Height Conversion Program
1
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download C++ Input and Output Operators: >> and <<, Manipulators, and Examples - Prof. Sandra Huert and more Study notes Computer Science in PDF only on Docsity!

C++ INTERACTIVE INPUT AND OUTPUT

Input

The extraction operator >> is used for general input of variable values. The extraction operator is defined for all the built-in basic C++ types. It is possible to input values for multiple variables in the same statement by chaining them together with the extraction operator. For each occurrence of >> you must supply the name of the variable where you want the input value assigned (a statement can’t end with >>). cin >> value1 >> value2; is the same as cin >> value1; cin >> value2; Rules for how C++ reads different types of values: int Skip any leading spaces or blank lines, read digits until encountering a character that is not valid in an integer value, like a blank space or a special character, or a decimal point, or a letter, or the end of the line (result of pressing Enter) double Skip any leading spaces or blank lines, read digits until encountering a character that is not valid in a floating-point value, like a blank space or a special character other than a decimal point, or a letter, or the end of the line. char Skip any leading spaces or blank lines and read the first non-blank character encountered. string Skip any leading spaces or blank lines and read characters until encountering a blank space or the end of the line.

When you’re reading from the keyboard, you should precede your input

statements with output statements explaining what it is that your program

is expecting the user of the program to enter – these are called prompting

messages. Otherwise, the cursor will be blinking on the output screen, but

the user of the program has no way of knowing what the program is waiting

for.

Prompting messages should be brief because people tend not to read instructions

very well. Sometimes it helps to give the user an example of the input the

program expects rather than to try and write out a long detailed description.

Some knowledge about the anticipated users of your program may give you

an idea of the amount of detail that would be necessary or desirable in your

instructions.

You can input the values your program needs in any order you want and in

any combination you want (one at a time, two at a time, etc.). I strongly

recommend reading only one value at a time because it greatly simplifies

the instructions and possibly helps to prevent errors by the user while keying

the input values. If you expect the user to enter multiple values without

additional instructions in between values, then you probably need to explain

about the spacing required. If you’re only asking for one value at a time,

spacing isn’t a problem.

// Monty Python

// Program 1

// CSCI 151 Height Conversion Program

// Dev C++ compiler

// This program will ask you for your first name and for how tall you are in feet and

// inches, and it will tell you how tall that is in total inches, in centimeters, and in

// meters.

#include

using namespace std;

const double CM_PER_INCH = 2.54;

const double INCHES_PER_FOOT = 12;

int main ()

string yourFirstName;

double feetTall;

double inchesTall;

double cmTall;

double metersTall;

cout << "Hi, what's your first name? ";

cin >> yourFirstName;

cout << "How tall are you, " << yourFirstName << "?" << endl;

cout << "For example, if you're 5 feet 10 inches tall," << endl;

cout << "Enter 5 when I ask for feet and 10 when I ask for inches" << endl;

cout << "Press the Enter key after you type the number for each "

<< "question" << endl << endl;

cout << "How many feet tall are you: ";

cin >> feetTall;

cout << feetTall << " feet and how many inches: ";

cin >> inchesTall;

cout << endl;

cout << feetTall << " feet " << inchesTall << " inches is" << endl;

inchesTall = feetTall * INCHES_PER_FOOT + inchesTall;

cmTall = inchesTall * CM_PER_INCH;

metersTall = cmTall / 100;

cout << inchesTall << " inches or " << cmTall << " centimeters or "

<< metersTall << " meters." << endl << endl;

system("pause");

return 0;

#include using namespace std; int main () { // value displayed: cout << '' << "I'm a sample string" << '' << endl; // * I’m a sample string * char ch = 'C'; int t = 273; cout << '' << ch << '' << endl; // * C * cout << '' << t << '' << endl; // * 273 * cout << '' << -t << '' << endl; // * -273 * double d2 = 123.456789; cout << '' << d2 << "" << endl; // * 123.457 * cout << '' << d2 * 100 << '' << endl; // * 12345.7 * cout << '' << d2 * 10000 << '' << endl; // * 1.23457e+006 * double d3 = 2.3e-4; cout << '' << d3 << '' << endl; // * 0.00023 * cout << '' << d3 / 10 << '' << endl; // * 2.3e-005 * // The point where the default switches from fixed to scientific varies from one // compiler to another. double d4 = 5.0; cout << '' << d4 << '' << endl; // * 5 * system("pause"); return 0; } To override any of C++'s default formatting, C++ provides manipulators which have special meaning in the context of input and/or output constructs. Each causes a corresponding library function to be called, which changes the state of the specified stream as requested. To use any of these manipulators, simply insert them within the I/O stream preceding the value they are to manipulate.

Manipulators Having No Parameters (defined in iostream.h )

Manipulator Purpose

endl Inserts a new-line and flushes the stream (output only) boolalpha Causes boolean values to be input/output as strings true and false noboolalpha Causes boolean values to be input/output as integers 1 and 0 (this is the default) fixed Causes float values to be displayed in fixed decimal format scientific Displays float values in exponential notation left Causes output to be left-justified right Causes output to be right-justified (this is the default) showpoint Shows the decimal point and trailing zeros for float values noshowpoint Suppresses display of decimal point for float values with a zero fractional part Displays trailing zeros for float values with a non-zero fractional part showpos Adds leading + to positive numbers noshowpos Does not add a leading + to positive numbers (this is the default)

Manipulators Having One Parameter (defined in iomanip.h )

Manipulator Purpose

setprecision (int p) Sets the number of digits displayed after a decimal point for floats (affects output only if the fractional portion of the number is nonzero) Note: setprecision may not work as expected unless used in combination with both fixed and showpoint manipulators. setw (int w) Sets field width for the next output value only setfill (int ch) Sets fill character (the default is blank)

Example of using manipulators: (all manipulators persist except for setw)

#include #include using namespace std; int main () { cout << '' << setw(8) << "HI MOM" << '' << endl; // 1

123456789012345678 (column positions)

* HI MOM* 1 right justify is the default, so it pads with blanks before value;

setw doesn’t also apply to the second asterisk printed cout << '' << left << setw(10) << "HI MOM" << '' << endl; // 2

123456789012345678 (column positions)

*HI MOM * 2 can ask to left justify instead; pad with blanks after value

cout << '' << setw(9) << 100.00 << '' << 123.426879 << ‘*’ << endl; // 3

123456789012345678 (column positions)

*100 123.427 3 left justifies numbers, too; no decimal point if fraction is 0;

field width not reused for second value; .426879 rounded to. cout << '' << right << setw(8) << "HI MOM" << '' << endl; // 4

123456789012345678 (column positions)

* HI MOM* 4 switch back to right justify again

cout << '' << setw(1) << "HI MOM" << '' << endl; // 5

123456789012345678 (column positions)

HI MOM 5 ignores field width if too small; prints entire value

// cout << ‘’ << setw(10) << setprecision(4) << 123.426879 << ‘’ << endl; // 6

123456789012345678 (column positions)

* 123.4* 6 right-justified; without fixed & showpoint, setprecision is just

the total # of digits to be printed cout << fixed << showpoint ; // these can be included in any output statement or by themselves

.426879 rounded to.

123.48 9 doesn’t round .48245 because next digit was only 2

123456789012345678 (column positions)

$***123.42 10 change fill character; precision of 2 persists from previous stmt;

no rounding because first digit lost is less than half

***123.4 11 fill char persists until changed; doesn’t round

will apply to values printed following the manipulator

5.00 5 12 with fixed & showpoint we get decimal point and trailing zeros;

but setprecision doesn’t apply to ints – would need typecast

Additional Functions for Specialized Output (defined in iostream.h)

put outputs one character or outputs the char equivalent of an

ASCII number

Examples:

cout.put('\n'); (move cursor to the beginning of the next line;

same as cout << endl;)

cout.put('A'); (display A)

cout.put(2); (display a smiley face – ASCII number of 2)

cout.put(‘\a’); (make the computer beep – \a is the escape

sequence for the alert char)

cout.put(65); (display A – 65 is the ASCII number for A)

Additional Functions for Specialized Input (defined in iostream.h)

Assume the declaration: char ch;

get does not skip leading whitespace but inputs the next character

( even if it is whitespace ).

cin.get (ch); inputs the next character waiting to be read and assigns

the character value read to the variable ch.

getline reads all chars (including blanks) from the current cursor/file

position until a newline is found. The newline is read but is not stored.

If input is Computer Science

and input is read by: getline(cin, s);

s has a value of "Computer Science".

If the same input were read with: cin >> s;

the value of s would only be "Computer" and the rest of the input

remains in the input stream waiting to be read by the next input

statement.

getline reads all chars (including blanks) from input stream and stores

them until a number of characters equal to the maximum length of a

string have been read, the end of file occurs, or the designated delimiter

is encountered, in which case the delimiter is read but is not stored.

getline(cin, s, ‘,’); reads all chars until it finds a comma. All chars read

up to the comma are assigned to s; the comma is skipped over, and the

next input begins with the next char after the comma.

ignore skips over a designated number of characters or terminates when

it finds a designated delimiter. The delimiter is skipped. You can specify

any non-negative number of characters and any character as a delimiter.

cin.ignore(80,'\n'); skips over the next 80 characters, or until it finds

the end-of-line character, whichever comes first. If it finds the end-of-line

character before it counts up to 80 characters, it skips the end-of-line

character, and the next character after it becomes the next character

waiting to be read.

peek returns a copy of the next character in the input stream (including

whitespace), but does not remove the character from the stream (that

character remains in the input stream to be read by the next input statement).