cout / cin - University of Kentuckykwjoiner/cs215/notes/IntroCinC... · 2020. 8. 18. · cin...

Preview:

Citation preview

Introduction to

is used to print to the screen in a C++

Console Application.

is used to read user input from the

keyboard in a C++ Console Application.

and are defined by the C++

standard library . To use these

utilites:

#include <iostream>

Additional utilities for formatting are in:

#include <iomanip>

is a stream from the application

(executing in memory) to the screen.

Characters are inserted into the stream and

“fall out” on the screen.

I/O manipulations may be used to format

the characters before they are written.

is a stream from the application

(executing in memory) to the screen.

Characters are inserted into the stream and

“fall out” on the screen.

I/O manipulations may be used to format

the characters before they are written.

cout << expression;

where expression is a literal, variable or

more complex expression that evaluates to

one value.

cout << expr1 << expr2 << ...

<< exprn;

is equivalent to:

cout << expr1;

cout << expr2;

...

cout << exprn;

Can vary greatly depending on the situation.

Make it clear to another programmer and

easy to maintain.

Good style:

cout << ”+-------+\n”;

cout << ”| Hello |\n”;

cout << ”+-------+\n”;

Good style:

cout << ”+-------+\n”

<< ”| Hello |\n”

<< ”+-------+\n”;

Poor style:

cout << ”+-------+\n| Hello |\n+-------+\n”;

Floating Point Numbers:

// print floats/doubles in decimal format with

// 2 digits past the decimal point.

// Prints nothing. In effect until changed.

cout << fixed << setprecision(2);

Field Widths:

// set total field with of a value

cout << setw(10) << ”Hello”;

Prints 5 spaces then 5 characters:

Hello

Field Widths:

// effect is only for 1 value

cout << setw(10) << ”Hello” << ”There”;

Prints 5 spaces then 5 characters then There

HelloThere

Justification:

// effect is until Justification is changed

cout << left << setw(10) << ”Hello”;

cout << right << setw(10) << ”There”;

Prints 5 chars, 5 spaces, 5 spaces, 5 chars

Hello (10 spaces) There

is a stream from the keyboard to the

console application (executing in memory)

Characters are inserted into the stream by

the user and are extracted by

(simple)

cin >> variable;

in general

variable = whatever is entered by the user;

in general

- halts execution of the program

- the user enters data and presses ENTER

- the data is converted to the data type of the

variable.

- the data entered is stored in the variable

- execution continues

specifically

Exactly how behaves depends on the:

- data type of the variable

- what is currently in "the stream", if anything.

- data type of the data entered by the user

For now, assume that for each :

- the user enters the correct data type

- the user enters NO SPACES/TABS/etc

- the user presses ENTER when done

Recommended