Expressions and Interactivity

advertisement
CS241, TSU
Expressions and Interactivity
by Li Ma
The cin Object
Gathering input from the user is normally a two-step process:
1. Use the cout object to display a prompt message on the screen
2. Use the cin object to read a value from the keyboard
cin is the standard input object, working with streams of data.




It causes a program to wait until data is typed at the keyboard and the [Enter] key is
pressed
It automatically converts the data read from the keyboard to the data type of the variable
used to store it
It may be used to gather multiple values (same types or different types) at once
The directive #include <iostream> is needed
Stream extraction operator (>>): send the input from cin to a variable
Mathematical Expressions
C++ allows you to construct complex mathematical expressions using multiple operators and
grouping symbols
An expression can be a literal, a variable, or a mathematical combination of constants and
variables. It can be used in a statement like assignment, cout, etc
The precedence and associativity of arithmetic operators
1. unary negation -: right-to-left
2. *, /, %: left-to-right
3. +, -: left-to-right
4. =: right-to-left
Parentheses can be used to force some operations to be performed before others
Straight-line form in C++ program: a/b instead of
𝑎
𝑏
No exponents in C++. Instead, the library function pow is used to raise a number to a power

Area = pow(4.0, 2.0); //it’s for Area = 42

The directive #include <cmath> is needed
1
CS241, TSU
Expressions and Interactivity
by Li Ma
Type Conversion
Hierarchy of Types (from highest to lowest, ranked by largest number they can hold)







long double
double
float
unsigned long
long
unsigned int
int
Type Coercion: automatic conversion of an operand to another data type


Promotion: convert to a higher type
Demotion: convert to a lower type
Coercion rules:
1. char, short, unsigned short automatically promoted to int
2. When operating on values of different data types, the lower one is promoted to the type
of the higher one.
3. When using the = operator, the type of expression on right will be converted to type of
variable on left
Overflow and Underflow
Occurs when assigning a value that is too large (overflow) or too small (underflow) to be held in
a variable
When overflow or underflow happens, variable contains value that is ‘wrapped around’ set of
possible values
Different systems may display a warning/error message, stop the program, or continue execution
using the incorrect value
Type Casting – Manual Data Type Conversion
A type cast expression lets you manually promote or demote a value
2
CS241, TSU

Expressions and Interactivity
by Li Ma
Useful for floating point division using ints:
double m;
m = static_cast<double>(y2-y1)/(x2-x1);

Useful to see int value of a char variable:
char ch = 'C';
cout << ch << " is "
<< static_cast<int>(ch);
Two older methods of creating type cast expressions are still supported in C++, although
static_cast is preferred

C-Style cast: data type name in ()
cout << ch << " is " << (int)ch;

Prestandard C++ cast: value in ()
cout << ch << " is " << int(ch);
Multiple Assignment and Combined Assignment
The operator = can be used to assign a value to multiple variables:
x = y = z = 5;
Value of = is the value that is assigned, and it associates right to left:
x = (y = (z = 5));
Look at the following statement, it adds 1 to the variable sum
sum = sum + 1;
The combined assignment operators provide a shorthand for the types of statements above.
The statement sum = sum + 1; is equivalent to sum += 1;
It is similar to other binary operators
3
CS241, TSU
Expressions and Interactivity
by Li Ma
Formatting Output
Stream manipulators can be used to control how output displays for numeric, string data:

size

position

number of digits
The directive #include <iomanip> is needed
Some stream manipulators affect just the next value displayed:

setw(x): print in a field at least x spaces wide.
o Use more spaces if field is not wide enough
Some affect values until changed again:

fixed: use decimal notation for floating-point values
o number of digits after the decimal point is fixed (by setprecision())

setprecision(x):
o used with fixed, print floating-point value using x digits after the decimal
o without fixed, print floating-point value using x significant digits

showpoint: always print decimal for floating-point values

left/right: causes subsequent output to be left/right justified
Working with Characters
Once cin object reads input, it will first put the input in the keyboard buffer, then may store it to
a memory location (variable).
When cin reads input, it passes over and ignores any leading whitespace characters (spaces, tabs,
or line breaks). So it

starts reading once it comes to the first nonblank character

stops reading when it gets to the next whitespace character
4
CS241, TSU
Expressions and Interactivity
by Li Ma
We can use a C++ function named getline to work around this problem. The getline function
reads the entire line, including leading and embedded spaces, and stores it in a string object.
string myString;
//declare a variable myString, which is an object of class string
getline(cin, myString);
//get the entire line from standard input (keyboard), and store it to myString
If we like to input just a single character, the object cin and the >> operator could be used. But in
the situation that the character for the [Enter] key, tab key, or spacebar should be the input, cin
<< does not work.
A built-in function (member function) named get for the cin object can help.
char ch;
//declare a char variable ch
cin.get(ch); or ch = cin.get(); //read any input character, and store it to ch
cin.get();
//pause the screen until the [enter] key is pressed, and does not store the character
Do not mix cin >> and cin.get. Otherwise, some input may be missed. The cin.ignore function
tells the cin object to skip one or more characters in the keyboard buffer.
cin.ignore();
//cin will skip only the very next character
cin.ignore(n, c);
//cin will skip n number of characters, or until the character c is encountered
Working with string Objects
C++ string objects have a number of member functions, length is one of them:
string thisString = “a test”;
//declare and initialize a string variable (object)
int size = thisString.lenth();
//get the length of the string stored in thisString, and store the result to an integer size
When the operator + is used with string operands, it concatenates strings, or joins them together
5
CS241, TSU
Expressions and Interactivity
by Li Ma
string theString1 = “Here ”;
string theString2 = “you ”;
string theString3 = “are!”;
//declare and initialize three (3) string variables (objects)
string theSentence;
//declare a string variable (object)
theSentence = theString1 + theString2;
//theSentence is “Here you ” now
theSentence = theSentence + theString3; or theSentence += theString3;
// theSentence is “Here you are!” now
More Mathematical Library Functions
The C++ runtime library provides several functions for performing complex mathematical
operations. See Table 3-13 on page 127 of the textbook.



require cmath header file
take double as input, return a double
Commonly used functions:
sin
Sine
cos
Cosine
tan
Tangent
sqrt
Square root
log
Natural (e) log
abs
Absolute value (takes and returns an int)
The C++ library has some functions to randomly generate numbers. These function require
cstdlib header file

rand(): returns a random number (integer) between 0 and the largest integer the compute
holds.
o yields same sequence of numbers each time program is executed on the same
computer system.
6
CS241, TSU

Expressions and Interactivity
by Li Ma
o must use srand() to randomize the result of rand()
srand(x): initializes random number generator with unsigned int x as the seed
Hand Tracing a Program
To hand trace a program, you will act as if you are the computer, executing a program


step through and “execute” each statement, one-by-one
record the contents of variables after statement execution, using a hand trace chart (table)
It is useful to locate logic or mathematical errors.
7
Download