25
1 Expressions and Interactivity Chapter 3 SJAllan 2005 Expressions and Interactivity 2 The cin Object Reads information from keyboard Causes program to wait until input has been entered and the [Enter] key has been pressed Is a stream object It is also the standard input object SJAllan 2005 Expressions and Interactivity 3 The cin Object Is used with >>, the stream extraction operator, that extracts data from the object on the left and stores it in the variable on the right cin >> variable; Automatically coverts the keyboard data to the data type of the variable Requires the iostream header file SJAllan 2005 Expressions and Interactivity 4 The cin Object Memory aid: >> (extraction) operator in cin << (insertion) operator in cout Appear to point in the direction information is flowing From a variable to cout to the output stream cout << variable; To a variable from cin from the input stream cin >> variable;

Expressions and Interactivity - Utah State Universitydigital.cs.usu.edu/~allan/CS1/Slides/Ch03.pdf · SJAllan 2005 Expressions and Interactivity 8 Program ... SJAllan 2005 Expressions

Embed Size (px)

Citation preview

1

Expressions and Interactivity

Chapter 3

SJAllan 2005 Expressions and Interactivity 2

The cin Object

Reads information from keyboard

Causes program to wait until input has been entered and the [Enter] key has been pressedIs a stream object

It is also the standard input object

SJAllan 2005 Expressions and Interactivity 3

The cin Object

Is used with >>, the stream extraction operator, that extracts data from the object on the left and stores it in the variable on the right

cin >> variable;

Automatically coverts the keyboard data to the data type of the variable

Requires the iostream header file

SJAllan 2005 Expressions and Interactivity 4

The cin ObjectMemory aid:

>> (extraction) operator in cin<< (insertion) operator in coutAppear to point in the direction information is flowingFrom a variable to cout to the output stream

cout << variable;To a variable from cin from the input stream

cin >> variable;

2

SJAllan 2005 Expressions and Interactivity 5

Program // This program reads the length and width of a rectangle.// It calculates the rectangle's area and displays // the value on the screen.#include <iostream>using namespace std;

int main ( void ){ int Length, Width, Area;

cin >> Length;cin >> Width;Area = Length * Width;cout << "The area of the rectangle is " << Area << endl;return 0;

} // main

What’s wrong with this program?

10 <Enter>20 <Enter>The area of the rectangle is : 200

It does not prompt the user.cin should be preceded with a cout that prints a prompt to the user describing the desired input from the keyboard.

SJAllan 2005 Expressions and Interactivity 6

Program#include <iostream>using namespace std;int main ( void ){ int Length, Width, Area;

cout << "This program calculates the area of a rectangle.\n";cout << "What is the length of the rectangle? ";cin >> Length;cout << "What is the width of the rectangle? ";cin >> Width;Area = Length * Width;cout << "The area of the rectangle is " << Area << ".\n";return 0;

} // main

This program calculates the area of a rectangle.What is the length of the rectangle? 10[Enter]What is the width of the rectangle? 20[Enter]The area of the rectangle is 200.

Note use of comment to identify what the bracket is closing

SJAllan 2005 Expressions and Interactivity 7

Entering Multiple Values

The cin object may be used to gather multiple values at once by having multiple extraction operators in the statement.

cin >> variable >> variable >> …;

SJAllan 2005 Expressions and Interactivity 8

Program#include <iostream>using namespace std;

int main ( void ){ int Length, Width, Area;

cout << "This program calculates the area of a rectangle.\n";cout << "Enter the length and width of the rectangle"

<< " separated by a space. \n";cin >> Length >> Width;Area = Length * Width;cout << "The area of the rectangle is " << Area << endl;return 0;

} // main

Notice one way to handle a long string.

This program calculates the area of a rectangle.Enter the length and width of the rectangle separated by a space.10 20 [Enter]The area of the rectangle is 200

3

SJAllan 2005 Expressions and Interactivity 9

Different Data Types – Program#include <iostream>using namespace std;

int main ( void ){ int Whole;

float Fractional;char Letter;

cout << "Enter an integer, a float, and a character: ";cin >> Whole >> Fractional >> Letter;cout << "Whole: " << Whole << endl;cout << "Fractional: " << Fractional << endl;cout << "Letter: " << Letter << endl;return 0;

} // main

What happens if we enter the data in the incorrect order?

SJAllan 2005 Expressions and Interactivity 10

Reading Strings

cin can read strings as well as numbersStrings are stored as C-stringsA C-string is commonly stored in a character array, a construct that consists of multiple values of the same data type

char Company[12];The above array can hold up to 12 different values rather than just one as we have seen with other variables

SJAllan 2005 Expressions and Interactivity 11

Entering Strings – Program #include <iostream>using namespace std;

int main ( void ){ char Name [8];

cout << "What is your name? ";cin >> Name;cout << "Good morning, " << Name << endl;return 0;

} // main

What is your name? Charlie[Enter]Good morning, Charlie

What happens if we enter a name longer than 7 characters or enter a name with a space in it?

SJAllan 2005 Expressions and Interactivity 12

Strings Again – Program // This program reads two strings into two character arrays.#include <iostream>using namespace std;

int main ( void ){ char First [16], Last [16];

cout << "Enter your first and last names and I will\n";cout << "reverse them.\n"; cin >> First >> Last;cout << Last << ", " << First << endl;return 0;

} // main

Enter your first and last name and I willreverse them.Steve Allan[enter]Allan, Steve

4

SJAllan 2005 Expressions and Interactivity 13

Notes on StringsIf a character array is intended to hold strings, it must be at least one character larger than the largest string that will be stored in it

Do you remember why?The cin object lets the user enter a string larger than the array can hold

If this happens, the string overflows the array’s boundaries and destroys other information in memory

If you wish the user to enter a string that has spaces in it, you cannot use this input method

SJAllan 2005 Expressions and Interactivity 14

OperatorsC++ operators:

Unary (1 operand)-5

Binary (2 operands) 13 – 7amount = 19.99;

Ternary (3 operands) Only one; we’ll look at it in Ch. 4

SJAllan 2005 Expressions and Interactivity 15

Arithmetic Operators

Used for performing numeric calculationsBinary arithmetic operators

+ addition- subtraction* multiplication/ division% modulus

SJAllan 2005 Expressions and Interactivity 16

/ Operator

/ (division) operator performs integer division if both operands are integerscout << 13 / 5; // displays 2cout << 97 / 7; // displays 13

If either operand is floating-point, the result is floating pointcout << 13 / 5.0; // displays 2.6cout << 91.0 / 7; // result is 13.0

5

SJAllan 2005 Expressions and Interactivity 17

% Operator

% (modulus) operator computes the remainder resulting from integer divisioncout << 13 % 5; // displays 3

% requires integers for both operandscout << 13 % 5.0; // compiler error

SJAllan 2005 Expressions and Interactivity 18

Summary Examples

%

/

*

-

+

EXAMPLEOPERATIONSYMBOL

addition sum = 7 + 3; =10

subtraction difference = 7 - 3; =4

multiplication product = 7 * 3; =21

division quotient = 7 / 3; =2

modulus remainder = 7 % 3; =1

SJAllan 2005 Expressions and Interactivity 19

Programming Style

One aspect is the visual organization of the source codeThis includes the use of spaces, tabs, blank lines, and meaningful variable namesAffects the readability, not the syntax, of the source code

SJAllan 2005 Expressions and Interactivity 20

Programming Style

Common elements to improve readability:Braces { } aligned verticallyIndentation of statements within a loop or a selection or a set of bracesBlank lines between definitions and other statementsLong statements wrapped over multiple lines with aligned operators

6

SJAllan 2005 Expressions and Interactivity 21

Standard and Prestandard C++

Older-style C++ programs:• Use .h at end of header files:

#include <iostream.h>• Do not use using namespace convention• May not compile with a standard C++

compiler

SJAllan 2005 Expressions and Interactivity 22

Mathematical Expressions

An expression is a programming element that has a valueAn expression can be a literal, a variable, or a mathematical combination of literals and variablesCan be used in assignment, cout and other statements

area = 2 * PI * radius;cout << "Area is " << ( length * width );

C++ allows you to construct complex mathematical expressions by using multiple operators, parentheses, and by grouping symbols

SJAllan 2005 Expressions and Interactivity 23

Arithmetic Expressions – Program#include <iostream>using namespace std;

int main ( void ){ float Numerator= 3.0, Denominator= 16.0;

cout << "This program shows the decimal equivalent of ";cout << "a fraction.\n"

<< "Numerator: " << Numerator << endl<< "Denominator: " << Denominator << endl<< "The decimal value is ";

cout<< ( Numerator / Denominator );return 0;

} // main

This program shows the decimal equivalent of a fraction.Numerator: 3.0Enter the denominator: 16.0The decimal value is 0.1875Again, note that a string constant

cannot extend over a line.Note the use of an expression in cout. Use parentheses around the expression to prevent “surprises” when using more advanced operators.

SJAllan 2005 Expressions and Interactivity 24

Precedence and Associativity

Precedence Refers to the hierarchy of operatorsWhen two operators share an operand, the operator with the higher precedence works first

Associativity Refers to the order in which an operator works with its operands, either left-to-right or right-to-left When two operators, sharing an operand, have the same precedence, they work according to their associativity

7

SJAllan 2005 Expressions and Interactivity 25

Precedence (Highest to Lowest) and Associativity of Arithmetic Operators

Operator Associativity

+ – (binary) left-to-right

* / % left-to-right

– (unary) right-to-leftPrecedence

lowestSJAllan 2005 Expressions and Interactivity 26

Examples of Arithmetic Expressions

6 – 3 * 2 + 7 – 1

4 + 17 % 2 – 1

8 + 12 * 2 – 4

10 + 2 / 2

5 + 2 * 4

ValueExpression

13

11

28

4

6

SJAllan 2005 Expressions and Interactivity 27

Examples of Arithmetic Expressions

(6 – 3) * 2 + (7 – 1)

(4 + 17) % 4 – 1

8 + 12 * (6 – 2 )

10 / (2 – 3)

(5 + 2) * 4

ValueExpression

28

-10

56

0

12

SJAllan 2005 Expressions and Interactivity 28

Converting Algebraic Expressions to Programming Statements

In C++, an operator is needed for all operations. In algebra we can say c =ab to indicate a is to be multiplied by b. In C++ we must say c = a * b;Parentheses are often needed, especially when an algebraic expression uses division.How would you write

Z=(4*(A-1) +2*B)/(3*C-2/(D+E));or

Z=((4*(A-1))+2*B)/(3*C-(2/(D+E)));

ED

23C

2B1)4(AZ

+−

+−= ?

8

SJAllan 2005 Expressions and Interactivity 29

Exponentiation and the C++Library

C++ does not have an exponentiation operator, an operator to raise to a powerThe pow() library function is used to raise a number to a powerA library function can be thought of as a special “routine” that performs a specific task

SJAllan 2005 Expressions and Interactivity 30

Function as “Black Box”

Another way to think of a function is as a “black box” that receives information from the arguments, performs a task, and returns information to the statement where the function call appears

powArgument 1 x=5

Argument 2 y=3

xy = 125 Result

SJAllan 2005 Expressions and Interactivity 31

Some Characteristics of Functions

The parentheses ( ) are necessary for a function Expressions inside the parentheses are the arguments of the function

Arguments are information being sent to the function

SJAllan 2005 Expressions and Interactivity 32

More Characteristics of Functions

Different functions have different numbers of argumentsA reference to a function within a statement is a function callThe result produced by the function is returned to where the function call appears in the program

9

SJAllan 2005 Expressions and Interactivity 33

The pow( ) FunctionHas two arguments and raises the first argument to the power of the second argumentThe function call pow(4,5) sends 4 and 5 to the function, which raises 4 to the fifth power and returns 1024 (45 = 4*4*4*4*4) It is designed to return a doubleRequires the cmath header file

#include <cmath>SJAllan 2005 Expressions and Interactivity 34

The pow( ) Function

//Using the pow function to calculate area of a square#include <iostream>#include <cmath>using namespace std;

int main( void ){ double area, side = 3;

area = pow( side, 2 );

cout<< "Area of square with side " << side<< " is " << area;

return 0;} // main

Needed for the pow( )function.

pow( )returns a double

Function call passes the value of side (3.0) and 2 to the pow function

Value 9.0 is calculated by pow and returned to the location of the function reference. The value of 9.0 is then assigned to area

Output: Area of square with side 3 is 9

SJAllan 2005 Expressions and Interactivity 35

When you Mix Apples and Oranges: Type Coercion

Operations are performed internally between operands of the same data typeWhen operands are of different data types, C++ automatically converts them to the same data type, sometimes impacting the results of calculations

SJAllan 2005 Expressions and Interactivity 36

Data Type Ranking

• long double• double• float• unsigned long• long• unsigned int• int

highest

lowest

Ranked by size of number that can be stored. Data types that hold larger numbers are ranked higher.

10

SJAllan 2005 Expressions and Interactivity 37

Data Type Ranking

Ranked by size of the number that can be stored

Data types that hold larger numbers are ranked higher

A variable is promoted to a higher rank and demoted to a lower rank

SJAllan 2005 Expressions and Interactivity 38

Type Coercion Rules:

Rule 1: chars, shorts, and unsigned shorts are automatically promoted to intRule 2: When an operator works with two values of different data types, the lower-ranking value is promoted to the type of the higher-ranking valueRule 3: When the final value of an expression is assigned to a variable, the value of the expression is converted to the data type of the variable

SJAllan 2005 Expressions and Interactivity 39

Example

Assume age is an int and factor is a float:What happens in the evaluation of expression

age * factor ?

age is promoted to float and the result of the expression is a float.

SJAllan 2005 Expressions and Interactivity 40

Exampleint j, k=5;float y= 3.7;j= k * y;What is stored in j?

18 k is promoted to float in the expression k*y, so the result is 18.5. But, the result is stored in j, an int, so value is truncated.

11

SJAllan 2005 Expressions and Interactivity 41

Overflow and Underflow

When a variable is assigned a value outside the range for its data type, the variable overflows or underflows

Overflow - when a variable is assigned a value that is too large for its data typeUnderflow - when a variable is assigned a value that is too small for its data type

Variable contains a value that is “wrapped around” the set of possible valuesDifferent systems do different things: you might see an error message, run-time error, or execution with incorrect value

SJAllan 2005 Expressions and Interactivity 42

Type Casting

The typecast operator, static_cast, allows the programmer to perform manual data type conversionFormat

static_cast<data type>(variable)

Value in variable is temporarily treated asdata type

SJAllan 2005 Expressions and Interactivity 43

Type Casting

What is the value of

static_cast<char>(65);

SJAllan 2005 Expressions and Interactivity 44

C-Style and Prestandard Type Cast Expressions

C-Style cast: data type name in ()cout << ch << " is " << (int)ch;

Prestandard C++ cast: value in ()cout << ch << " is " << int(ch);

Both are still supported in C++ but static_cast is preferred

12

SJAllan 2005 Expressions and Interactivity 45

The Power of Constants

Constants may be given names that symbolically represent them in a program

Use named constants instead of “magic numbers” in your programs

When naming a constant, the “tradition” is to use only uppercase letters in the name

That makes it easy to identify constants in the programConsider this a “programming style rule”

SJAllan 2005 Expressions and Interactivity 46

Named Constants in C++When using the const qualifier to declare a named constant, the named constant is a variable whose content is “read-only”… which means?

The value of a named constant cannot be changed within the program.

SJAllan 2005 Expressions and Interactivity 47

Named Constants in C++

When using the const qualifier in declaring a variable, the variable must be initialized when declared

const float INTERESTRATE = 0.09;

SJAllan 2005 Expressions and Interactivity 48

Constants – Program #include <iostream>#include <cmath>using namespace std;int main ( void ){ const float PI = 3.14159;

double Area, Radius;

cout << "This program calculates the area of a circle.\n";cout << "What is the radius of the circle? ";cin >> Radius;Area = PI * pow( Radius, 2 );cout << "The area is " << Area;return 0;

} // main

In this program, PI is a constant and its value cannot be changed.

Why is the cmath header file included?

13

SJAllan 2005 Expressions and Interactivity 49

The #define DirectiveThe older C-style method of creating named constants is with the preprocessor #define directive Remember that preprocessor directives cause the source code to be modified before compilationWhat does that mean?

SJAllan 2005 Expressions and Interactivity 50

The #define DirectiveConstants created with the #define directive are not variables; the text is substituted. (Note there is no type declaration.)For example: in #define PI 3.14159PI is a named constant and its value is 3.14159. Any time PI is appears in the program, the preprocessor replaces “PI” with “3.14159”Caution: don’t put a “;” at the end of the #define directive.

If you do, it becomes part of the constant

SJAllan 2005 Expressions and Interactivity 51

#define Statement – Program #include <iostream>#include <cmath>using namespace std;#define PI 3.14159

int main ( void ){ double Area, Radius;

cout << "This program calculates the area of a circle.\n";cout << "What is the radius of the circle? ";cin >> Radius;Area = PI * pow(Radius, 2);cout << "The area is " << Area;return 0;

} // main

This shows the use of the #define statement.

DON’T USE IT; rather use the const qualifier.

SJAllan 2005 Expressions and Interactivity 52

Multiple Assignment and Combined Assignment

Multiple assignment means that the same value is assigned to several variables in one statement

A = B = C = D = 12;Store1 = Store2 = Store3 = BegInv;

Assignment works from right to left

14

SJAllan 2005 Expressions and Interactivity 53

Same Variable on Both Sides of an Assignment Statement

Assume x is an int with value 6 at the beginning of each statement.

Makes x the remainder of x / 4x = x % 4;

Divides x by 2x = x / 2;

Multiplies x by 10x = x * 10;

Subtracts 3 from xx = x – 3;

Adds 4 to xx = x + 4;

x afterWhat it DoesStatement

10

3

60

3

2

SJAllan 2005 Expressions and Interactivity 54

Combined Assignment Operators

c %= 3;%=

a /= b;/=

z *= 10;*=

y -= 2;-=

x += 5;+=

Equivalent To

Example UsageOperator

x = x + 5;

y = y – 2;

z = z * 10;

a = a / b;

c = c % 3;

SJAllan 2005 Expressions and Interactivity 55

Combined Assignment Operatorswith more complex expressions

c %= x - 3;%=

a /= b + 5;/=

z *= 10 - c;*=

y -= a * 2;-=

x += a + 5;+=

Equivalent ToExample UsageOperator

NOTE: Regular math operators have higher precedence than the combined assignment operators.

x = x + (a+5);

y = y – (a*2);

z = z * (10-c);

c = c % (x-3);a = a / ( b+5);

SJAllan 2005 Expressions and Interactivity 56

Formatting OutputThe cout object provides ways to format data as it is being displayed, affecting the way data appears on screen, but not how it is stored Can control how output displays for numeric, string data in terms of

WidthPositionNumber of digits/characters

This is done with stream manipulators

15

SJAllan 2005 Expressions and Interactivity 57

Output Stream ManipulatorsSome manipulators affect just the next value displayed:

setw( x ): print in a field at least x spaces wide. Use more spaces if field is not wide enough

Some manipulators affect values until changed again; they are persisent

left and right: used with setw( x ) to left- or right-justify data in the field of size x

fixed: use decimal notation for floating-point values

setprecision( x ): when used with fixed, print floating-point value using x digits after the decimal. Without fixed, print floating-point value using x significant digits

showpoint: always print decimal for floating-point values

SJAllan 2005 Expressions and Interactivity 58

Default Formatting – Program#include<iostream>using namespace std;int main ( void ){ int Num1 = 2897, Num2 = 5, Num3 = 837, Num4 = 34,

Num5 = 7, Num6 = 1623, Num7 = 390, Num8 = 3456, Num9 = 12345;

// Display the first row of numberscout << Num1 << " " << Num2 << " " << Num3 << endl;

// Display the second row of numberscout << Num4 << " " << Num5 << " " << Num6 << endl;

// Display the third row of numberscout << Num7 << " " << Num8 << " " << Num9 << endl;

return 0;} // main

2897 5 83734 7 1623390 3456 12345

SJAllan 2005 Expressions and Interactivity 59

setw() Stream Manipulator –Program

#include <iostream>#include <iomanip>using namespace std;

int main ( void ){ int Num1 = 2897, Num2 = 5, Num3 = 837,

Num4 = 34, Num5 = 7, Num6 = 1623,Num7 = 390, Num8 = 3456, Num9 = 12345;

// Display the first row of numberscout << setw( 4 ) << Num1 << " ";cout << setw( 4 ) << Num2 << " ";cout << setw( 4 ) << Num3 << endl;

The file iomanip is needed for the setw

function.

setw() establishes a print field of specified

width only for the value immediately

following

The 4 in () is the field width: minimumnumber of positions

in the print field.SJAllan 2005 Expressions and Interactivity 60

setw() Stream Manipulator –Program (cont)

// Display the second row of numberscout << setw( 4 ) << Num4 << " ";cout << setw( 4 ) << Num5 << " ";cout << setw( 4 ) << Num6 << endl;// Display the third row of numberscout << setw( 4 ) << Num7 << " ";cout << setw( 4 ) << Num8 << " ";cout << setw( 4 ) << Num9 << endl;return 0;

} // main

Output:2897 5 837

34 7 1623390 3456 12345

Fields are padded with leading spaces

Values are right-justified

cout overrides setw() if the field width is not large enough for the value to be displayed.

Let’s look at another setwexample along with the left manipulator.

16

SJAllan 2005 Expressions and Interactivity 61

fill and setfill

Sometimes we don’t want the fill character to be a blank – the defaultWe can change the fill character in one of two ways:

fill – cout.fill( c );c is a character or a character constant

setfill – cout << setfill( c );cout.fill( '@' );cout << setfill( '*' );

SJAllan 2005 Expressions and Interactivity 62

Precision

Floating point values may be rounded to a number of significant digits, or precision, which is the total number of digits that appear before and after the decimal point

SJAllan 2005 Expressions and Interactivity 63

Using setprecision() without fixed

setprecision(2)34.28596

setprecision(4)109.5

setprecision(5)21

setprecision(3)28.92786

Value DisplayedManipulatorNumber

28.9

21

109.5

34

SJAllan 2005 Expressions and Interactivity 64

Member FunctionsFormatted input is performed using the setw() stream manipulator and member functions of the cin objectA member function is a C++ procedure that is part of an objectPackaging data and procedures together within an object is called encapsulationA member function causes the object to perform an actionCalling a member function is also called passing a message to the object

17

SJAllan 2005 Expressions and Interactivity 65

cin Member Functions

Needed because cin skips whitespace characters, including tab, blank, carriage return, newline generated by [Enter]

cin.getline(): reads a line of input, up to the newline charactercin.get(): reads one character, any character, including whitespacecin.ignore(): skips over characters in the keyboard buffer.

SJAllan 2005 Expressions and Interactivity 66

setw() in cinCan specify a field width for cinUseful when reading string data to be stored in a character array to avoid “overrunning” the end of the array:

char fName[10];cout << "Enter your name: ";cin >> setw(10) >> fName;

cin reads one less character than specified in setw() manipulator

SJAllan 2005 Expressions and Interactivity 67

Reading a “Line” of Inputcin.getline( array name, array size );cin.getline( line, 20 );

The first parameter, line, is the name of the previously declared array where the input is placedThe second parameter, 20, is the length of the arraycin.getline reads up to one character less than the number (second parameter), including spaces, leaving room for the null terminator

SJAllan 2005 Expressions and Interactivity 68

cin.getline – Program // This program demonstrates cin's getline member function.#include <iostream>using namespace std;

int main( void ){ char String [81];

cout << "Enter a sentence: ";cin.getline( String, 81 );cout << "You entered " << String << endl;return 0;

} // main

Enter a sentence: To be, or not to be.[Enter]You entered To be, or not to be.

Why cin.getline?

Because cin stops reading at a whitespace, including a blank, space, tab or the carriage return, [Enter].

18

SJAllan 2005 Expressions and Interactivity 69

Reading a Character –Program

#include <iostream>using namespace std;int main ( void ){ char Ch;

cout << "Type a character and press Enter: ";cin >> Ch;cout << "You entered " << Ch << endl;return 0;

} // main

Type a character and press Enter: A[Enter]You entered A

NOTE: The extraction operator >> requires the entry of a character and it ignores all leading whitespace characters. So, the program will not proceed if the [Enter] key, for example, were typed.

SJAllan 2005 Expressions and Interactivity 70

Pausing a Program #include <iostream>using namespace std;

int main( void ){ char Ch;

cout << "This program has paused. Press enter to continue.";cin.get( Ch );cout << "Thank you!" << endl;return 0;

} // main

OUTPUT:This program has paused. Press enter to continue.[Enter]Thank you!

The cin.get member function reads the first character entered, even if it is a whitespace character.

SJAllan 2005 Expressions and Interactivity 71

cin.get() – Program #include <iostream>using namespace std;

int main ( void ){ char Ch;

cout << "Type a character and press Enter: ";cin.get( Ch );cout << "You entered " << Ch << endl;cout << "Its ASCII code is " << static_cast<int>( Ch ) << endl;

} // mainThis is almost the same as cin >>, but it always reads the first character, even if it is a whitespace character.

Output:Type a character and press Enter: [Enter]You entered

Its ASCII code is 10

Why the blank line????

SJAllan 2005 Expressions and Interactivity 72

Mixing cin >> and cin.get(), cin.getline()

The Problem:Using cin.get() or cin.getline() after using cin causes a problemThe program appears to skip the cin.get()/cin.getline() and continues with the following statement

19

SJAllan 2005 Expressions and Interactivity 73

Mixing cin >> and cin.get, cin.getline

The Reason for the ProblemUser’s keystrokes are stored in keyboard bufferPressing the [Enter] key after inputting the number causes the newline character to be stored in the keyboard buffercin >> reads from the buffer, up to the newlinecharacterThe following cin.get(ch) or cin.getline(strng, #) reads the newline character from the buffer, stores it in the named variable and the program moves on

SJAllan 2005 Expressions and Interactivity 74

Mixing cin >> and cin.get, cin.getline

The SolutionThe ignore member function tells cin to ignore characters in the keyboard buffer

cin.ignore( n, c ); where n a number and c is a character, tells cin to ignore the next n characters in the keyboard buffer, unless the character stored in c is encountered before all n characters have been skipped

Example: cin.ignore( 20, '\n' ); skips the next 20 chars in the input buffer or until a newline is encountered, whichever comes first

cin.ignore(); skips the very next character in the input buffer

SJAllan 2005 Expressions and Interactivity 75

More Mathematical Library Functions

The C++ runtime library provides several functions for performing complex mathematical operations

SJAllan 2005 Expressions and Interactivity 76

Mathematic Functions

Tangent of the argumenty = tan( x );

Square root of the argumenty = sqrt( x );

Sine of the argumenty = sin( x );

Base-10 logarithm of the argumenty = log10( x );

Natural logarithm of the argumenty = log( x );

Floating modulusy = fmod( x, z );

Exponential of the argumenty = exp( x );

Cosine of the argumenty = cos( x );

Absolute value of the argumenty = abs( x );

DescriptionFunction

All these functions return doubles, except abs(),which returns int.

sin(), cos() and tan() require the angle measured in radians as the argument, where 2Π radians = 360°

How would you convert an angle of 60 ° to radians?

20

SJAllan 2005 Expressions and Interactivity 77

Mathematical Functions – Program

#include <iostream>#include <cmath>using namespace std;int main ( void ){ float A, B, C;

cout << "Enter the length of side A: ";cin >> A;cout << "Enter the length of side B: ";cin >> B;C = sqrt( pow( A, 2.0 ) + pow( B, 2.0 ) );cout << fixed << setprecision( 2 )

<< "The length of the hypotenuse is ";cout << C << endl;return 0;

} // main

Enter the length of side A: 5.0 [Enter]Enter the length of side B: 12.0 [Enter]The length of the hypotenuse is 13.00

SJAllan 2005 Expressions and Interactivity 78

Random Numbers

Sometimes it is necessary to use random numbers, as in simulations or gamesThis is done with a call to the rand() function (from the cstdlib library)A call to srand( seed ) seeds the random number generator

This allows the generator to give different sequencesWithout srand( seed ), the sequence is the same on every run of the program

SJAllan 2005 Expressions and Interactivity 79

Random Numbers – Program #include <iostream>#include <cstdlib>using namespace std;int main ( void ){ unsigned Seed;

cout << "Enter a seed value: ";cin >> Seed;srand(Seed);cout << rand() << endl;cout << rand() << endl;cout << rand() << endl;return 0;

} // main

OUTPUT RUN 1:Enter a seed value: 517313203621622

OUTPUT RUN 2:Enter a seed value: 165540296639920

OUTPUT RUN 3:Enter a seed value: 517313203621622

NOTE: A given seed produces the same resultsevery time.

cstdlib needed for rand()

SJAllan 2005 Expressions and Interactivity 80

Seeding the Random Number Generator

The book illustrates asking the user for a seed, but this seems a little clumsy A more standard way is to use the time of day as a seed.

This way you get different values each time without having to burden the user with supplying a seed.This is done as follows:

#include <ctime>…srand( time( 0 ) ); // use current time as a seed to rand…. rand()

21

SJAllan 2005 Expressions and Interactivity 81

Generating Random Numbers within Range 1-max

To generate a value y, 1 ≤ y ≤ Max

where 1 is the lower limit and Max the upper limit of the desired range

y= 1 + rand() % Max;

Write a statement that generates an integer between 1 and 100 and explain how it works

SJAllan 2005 Expressions and Interactivity 82

Generating Random Numbers within Range min to max

What do I have to do to generate a random number y, where

min ≤ y ≤ max? How many different possible values do I need to generate?

(max - min + 1)How can I generate that many possible random numbers?

rand() % (max – min + 1)

SJAllan 2005 Expressions and Interactivity 83

Generating Random Numbers within Range min to max

rand() % (max – min + 1) gives one of (max-min+1) random numbers in the range 0 tomax-minIf min is added to the beginning and end, the range becomes

min to [(max – min) + min], which simplifies to a range of min to max.So, to generate a random number, y, in the range min ≤ y ≤ max, use

y = min + rand() % (max – min + 1) SJAllan 2005 Expressions and Interactivity 84

Practice Problem: Math TutorWrite a program that can be used as a math tutor for a young student. The program should display two random numbers (between 1 and 999, inclusive) to be added, such as

27 + 432 =

The program should then pause while the student works on the problem. When the student is ready to check the answer, he or she should be prompted to press the [Enter] key and the program displays the problem with the solution

27 + 432 = 459

22

SJAllan 2005 Expressions and Interactivity 85

FilesA file is a collection of related information, usually stored on a computer’s diskInformation and data can be saved to files and then later reusedC++ uses file stream objects for implementing file access; the user defines these file stream objects, which are similar to the cin and cout objectsStreams of data can be read from an (input) file into variables by an input file stream objectStreams of information can be sent from variables to an (output) file by an output file stream object

SJAllan 2005 Expressions and Interactivity 86

Description of File Data Types

Can be used to create a file and allows reading from and writing to the file.fstream

Can be used to open an existing file and allows reading information from the file, i.e., information in the file can be copied to variables in the program.

ifstream

Can be used to create a file (or truncate an existing file) and allows writing information to the file, i.e., information in variables in the program can be copied to the file.

ofstream

DescriptionFile Stream Data Type

File usage requires the fstream header file:

SJAllan 2005 Expressions and Interactivity 87

Steps for Simple File Input and Output

1. Define one or more file stream objects (fso) of data types ofstream, ifstream, and/or fstream.

2. Open the file: open an existing file or or create a new file.

3. Read information from or write information to the file or both.

4. Close the file.

SJAllan 2005 Expressions and Interactivity 88

Defining a File Stream Object

Include the preprocessor statement#include <fstream>

Define the data type of the fsoifstream in;ofstream out;fstream inout;

in is of data type ifstream; any file associated with it can be read from.

out is of data type ofstream; any file associated with it can be written to.

inout is of data type fstream; any file associated with it can be written to and read from.

23

SJAllan 2005 Expressions and Interactivity 89

Opening a FileA file must be opened before it can be used.

Opening a file associates an external file name (one known by the operating system) with the internal file name that was declared in C++.

This is done with the open member function internal filename.open(external filename)

ex. in.open( "data.txt" );in.open( "a:\\data.txt" );

out.open( "c:\\temp\\results.dat" );

SJAllan 2005 Expressions and Interactivity 90

String Variable as Argument of open

A string variable may be used as the argument to open.… #include <fstream>… ifstream in;

char filename[25];cout << "Enter the input file name :";cin >> filename;in.open( filename );

SJAllan 2005 Expressions and Interactivity 91

Reading From / Writing To a File

Reading is done in a similar manner as when using cin, but instead of the cin object, you use the file stream object you declared of type ifstream.

in >> Num;Writing is done in a similar manner as when using cout: but instead of the cout object, you use the file stream object you declared of type ofstream

out << Num;SJAllan 2005 Expressions and Interactivity 92

Closing a File

Although the files are supposed to be closed automatically by C++, it is good practice to close the files yourself.Closing a file is done with the closemember function:

in.close();out.close();

24

SJAllan 2005 Expressions and Interactivity 93

Using Files – Program #include <iostream>#include <fstream>using namespace std;int main ( void ){ ifstream in;

ofstream out;int length, width, area;

in.open( "dimensions.txt" );out.open( "results.txt" );

SJAllan 2005 Expressions and Interactivity 94

Using Files – Program (cont)

cout << "Writing to the file.";in >> length >> width;area = length * width;out << "Area of rectangle 1: " << area << endl;

in >> length >> width;area = length * width;out << "Area of rectangle 2: " << area << endl;

in.close();out.close();return 0;

} // main

What will be output for input file of

10 2

5 7

SJAllan 2005 Expressions and Interactivity 95

Using Files – Output

Contents of the file dimensions.txt:10 25 7Output to the cout object: (to screen)Writing to the file.Contents of the file results.txt:Area of rectangle 1: 20Area of rectangle 2: 35

SJAllan 2005 Expressions and Interactivity 96

Another Way to Open Files

ifstream in ( "dimensions.txt" );ofstream out ( "results.txt" );

25

SJAllan 2005 Expressions and Interactivity 97

Creating an input file

To create an input file:Use the editor in Visual Studio.NETUse a text editor like NotePad

SJAllan 2005 Expressions and Interactivity 98

Programming ProblemA county collects property taxes on the assessment value of property, which is 60% of the property’s actual value. If an acre of land is valued at $10,000, its assessment value is $6,000. The property tax is then 64¢ for each $100 of the assessment value. The tax for the acre assessed at $6,000 will be $38.40. Write a program that gets the actual value of a piece of property from a file named actual.txt and writes all information to the file result.txt.