1 / 53

Starting Out with C++ Early Objects Seventh Edition

Chapter 3: Expressions and Interactivity. Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda. A. Standard Input. Input using keyboard ( cin) - extraction operator >> - other I/O functions, why?. The >> Operator.

elsar
Download Presentation

Starting Out with C++ Early Objects Seventh Edition

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 3: Expressions and Interactivity Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda

  2. A. Standard Input Input using keyboard (cin) - extraction operator >> - other I/O functions, why?

  3. The >> Operator • When ENTER key pressed, keyboard input goes to the input buffer in RAM, where it is stored as characters 123TomBrown72. 5eol 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 10 position • >> extracts characters from the input buffer and converts them into the data type of the variable int count; cout << "How may chairs in the room? "; cin >> count; • String “123” converted to whole number (int) 123 and stored into variable count. Next >> starts at pos 5 (space)

  4. The >> Operator • Can be used to read multiple values from keyboard cin >> height >> width; • Values must be separated by whitespace (space, tab, end-of-line [ENTER], end-of-file). • Multiple values need not all be of the same type • Order is important; first value entered is stored in first variable, etc.

  5. Other Input Functions • >> operator DOES NOT read WHITESPACE • Skipsor stops on space, tab, end-of-line, end-of-file • Skips over leading white space; • Stops on trailing white space. • To read any single char V (incl. whitespace) • cin.get(V) • To skip input characters: • cin.ignore(); // one character. • cin.ignore(n); // n characters.

  6. Character Input Reading in a character char ch; cin >> ch; // Reads in any non-blank char cin.get(ch); // Reads in any char cin.ignore(); // Skips over next char in // the input buffer

  7. String Input Reading in a string object string str; cin >> str; // Reads in a string // with no blanks getline(cin,str); // Reads in a string // that may contain // blanks

  8. String Input • >> operator can NEVER read strings that contain WHITESPACE • Skipsor stops on space, tab, end-of-line, end-of-file • To read string S (which may contain whitespace) • string S; • getline(cin, S); • How it works: reads all characters from cursor (5) to the end-of-line character (20), but does not store the eoln character. 123TomBrown72. 5eol 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 20position getline(cin, S); S = “ TOM BROWN 72.5”

  9. Working with Characters and String Objects char: holds a single character string: holds a sequence of characters Both can be used in assignment statements Both can be displayed with cout and <<

  10. C. Expressions and Type Conversion Expression  specifies a way to get a value • Constants/literals: 4 (value is 4) “fat cat” (value is fat cat) • Variables hold/produce values: X = 15.2; … cout << X; (value is 15.2) • Operators produce values (e.g., arithmetic, >>): 3 + 2  Add value 3 to value 2  value is 5 • Math functions produce values: sqrt(4.0)  Compute square root of 4.0  2.0 pow(1.5,2)  Compute square of 1.5  1.5x1.5 = 2.25

  11. C. Expressions and Type Conversion Where can expressions occur? Wherever a value is needed. • To initialize a declared variable: int x; // Initial value unknown (???). float q = 12.5; // Initial value 12.5. • Output: cout << q << ‘ ‘ << 2 * q; // 3 values: 12.5, char ‘ ‘, 25.0 • Input: cin >> x;  Add value 3 to value 2  value is 5

  12. C. Expressions and Type Conversion Arithmetic Expressions • One or more arithmetic operators • Operators require operands (things to work on) Binary operators (+ - * /): 3 + 2 (3 is left operand) • Produce new values that can be … • displayed (cout << 3+2*4 …) • stored into a variable ( p = 4*x – 9; ) • used to compute other values (pow(4*x-9,0.5))

  13. 3.2 Mathematical Expressions An expression can be a constant, a variable, or a combination of constants and variables combined with operators Can create complex expressions using multiple mathematical operators Examples of mathematical expressions: 2 height a + b / c

  14. This is an expression These are expressions Using Mathematical Expressions • Can be used in assignment statements, with cout, and in other types of statements • Examples: area = 2 * PI * radius; cout << "border is: " << (2*(l+w));

  15. Evaluate 2nd Evaluate 1st Evaluate 3rd Order of Operations Do first: Do next: Do last: • In an expression with more than one operator, evaluate in this order - (unary negation) in order, left to right * /% in order, left to right +- in order, left to right • In the expression 2 + 2 * 2 – 2 ,

  16. Associativity of Operators • Implied grouping/parentheses • - (unary negation) associates right to left -5  -5; - -5  - (-5)  5; - - - 5 = -(-(-5)) = - (+5)  -5 • */%+- all associate left to right 3 + 2 + 4 + 1 = (3 + 2) + 4 + 1 = ((3+2)+4)+1 =(((3+2)+4) + 1) • parentheses () can be used to override the order of operations 2 + 2 * 2 – 2 = 4 (2 + 2) * 2 – 2 = 6 2 + 2 * (2 – 2) = 2 (2 + 2) * (2 – 2) = 0

  17. Algebraic Expressions • Multiplication requires an operator Area = lw is written as Area = l * w; • There is no exponentiation operator Area = s2 is written as Area = pow(s, 2); (note: pow requires the cmath header file) • Parentheses may be needed to maintain order of operations is written as m = (y2-y1)/(x2-x1);

  18. More Mathematical Library Functions These require cmath header file Take double arguments and return a double Commonly used functions

  19. More Mathematical Library Functions • These require cstdlib header file • rand • Returns a random number between 0 and the largest int the computer holds • Will yield same sequence of numbers each time the program is run • srand(x) • Initializes random number generator with unsigned int x • Should be called at most once in a program

  20. D. How Assignment Works 3 X 7 X Pattern: var = expression; int X = 3; X = 4 * 2.5 – 3; // int X; Meaning: 3-step process (1) evaluate expression on right-hand-side. X = 4 * 2.5 – 3;  rhs = 10.0 – 3 = 7.0 (float) (2) convert value to data type of left-hand-side. 7.0 (float)  7 (int) (3) store converted value into variable. (int) X  7 (int)

  21. Automatic (Implicit) Type Conversion Arithmetic operators require operands of the same type If not of the same type, C++ will automatically convert one to be the type of the other This can impact the results of calculations

  22. Hierarchy of Data Types long double double float unsigned long long unsigned int int unsigned short short char Highest Lowest Ranked by largest number they can hold

  23. Type Coercion • Coercion: automatic conversion of an operand to another data type • Promotion: converts to a higher type float p; p = 7;  7 (int) converted to float 7.0 • Demotion: converts to a lower type int q; q = 3.5;  3.5 (float) converted to int 3

  24. Coercion Rules • char, short, unsigned short are automatically promoted to int • When operating on values of different data types, the lower one is promoted to the type of the higher one. • For the assignment operator = the type of expression on right will be converted to the type of variable on left

  25. Explicit Type Conversion • Also called type casting • Used for manual data type conversion • Format static_cast<type>(expression) • Example: cout << static_cast<char>(65); // Displays 'A'

  26. More Type Casting Examples char ch = 'C'; cout << ch << " is stored as code " << static_cast<int>(ch); gallons = static_cast<int>(area/500); avg = static_cast<double>(sum)/count;

  27. Older Type Cast Styles 21 intVol1 21.0 intVol1 double Volume = 21.58, dblVol; int intVol1, intVol2; intVol1 = (int) Volume; // C-style // cast // PREFERRED! dblVol=double(intVol1); //Prestandard // C++ style // cast

  28. E. Variations on Assignment Statements Multiple: Assign multiple variables at same time 3 2 1 X = Y = Z = 3 +5; X = (Y = (Z = 3+5) ); 8 (1) Z = 8; (2) Y = Z; [value 8] (3) X = Y; [value 8] NOTE: Right-to-Left associativity!

  29. Done Done Done 3rd 2nd 1st Multiple Assignment • The assignment operator (=) can be used more than 1 time in an expression x = y = z = 5; • Associates right to left x = (y = (z = 5));

  30. Combined Assignment • Also consider it “arithmetic” assignment • Updates a variable by applying an arithmetic operation to a variable • Operators: +=-=*=/=%= • Example: sum += amt; is short for sum = sum+amt; p += 3 + y; means p = p+(3+y);

  31. More Examples x += 5; means x = x + 5; x -= 5; means x = x – 5; x *= 5; means x = x * 5; x /= 5; means x = x / 5; x %= 5; means x = x % 5; RULE: The right hand side is evaluated first, then the combined assignment operation is done. x *= a + b;means x = x * (a + b);

  32. F. Formatting Output #include <iomanip> Concepts: - field - width - alignment - padding/fill - numeric formatting Pattern: << manipulators << expression.

  33. Formatting Output • Can control how output displays for numeric and string data • size • position • number of digits • Requires iomanip header file

  34. Stream Manipulators • Used to control features of an output field • Some affect just the next value displayed • setw(x): Print in a field at least x spaces wide. Use more spaces if specified field width is not big enough.

  35. Stream Manipulators • Some affect values until changed again • fixed:Use decimal notation (not E-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 point for floating-point values. • left, right:left-, right justification of value

  36. Manipulator Examples const float e = 2.718; float price = 18.0;Displays cout << setw(8) << e << endl;^^^2.718 cout << left << setw(8) << e << endl;2.718^^^ cout << setprecision(2); cout << e << endl;2.7 cout << fixed << e << endl;2.72 cout << setw(6) << price;^18.00

  37. H. C-strings C-string: char S[40]; // maxlength = 39 C++ string: string S; // NO max length. Concepts: - A string with maximum length - Similar to C++ string class I/O operators >> << - Different: No assignment operator = I/O function cin.getline must be told max length cin.getline(Cstr, 1+max#chars) e.g.: cin.getline(S, 40);

  38. H o t \0 3.10 Using C-Strings • C-string is stored as an array of characters • Programmer must indicate maximum number of characters at definition const int SIZE = 5; char temp[SIZE] = "Hot"; • NULL character (\0) is placed after final character to mark the end of the string • Programmer must make sure array is big enough for desired use; temp can hold up to 4 characters plus the \0.

  39. C-String Input • Reading in a C-string const int SIZE = 10; char Cstr[SIZE]; cin >> Cstr; // Reads in a C-string with no // blanks. Will write past the // end of the array if input string // is too long. cin.getline(Cstr, 10); // Reads in a C-string that may // contain blanks. Ensures that <= 9 // chars are read in. • Can also use setw() and width() to control input field widths

  40. C-String Initialization vs. Assignment • A C-string can be initialized at the time of its creation, just like a string object const int SIZE = 10; char month[SIZE] = "April"; • However, a C-string cannot later be assigned a value using the = operator; you must use the strcpy() function char month[SIZE]; month = "August" // wrong! strcpy(month, "August"); //correct

  41. G. Files #include <fstream> Concepts: - file is external (has a name) - C++ stream is internal, but connects to outside (cin keyboard; cout monitor) (ifstream input file; ofstream  output file - Housekeeping: Open (connect) / Close (disconnect) File name must be C-string width - alignment - padding/fill - numeric formats

  42. Introduction to Files Can use a file instead of keyboard for program input Can use a file instead of monitor screen for program output Files are stored on secondary storage media, such as disk Files allow data to be retained between program executions

  43. What is Needed to Use Files • Include the fstream header file • Define a file stream object • ifstream for input from a file ifstream inFile; • ofstream for output to a file ofstream outFile;

  44. Open the File • Open the file • Use the open member function inFile.open("inventory.dat"); outFile.open("report.txt"); • Filename may include drive, path info. • Output file will be created if necessary; existing output file will be erased first • Input file must exist for open to work

  45. Use the File • Use the file • Can use output file object and << to send data to a file outFile << "Inventory report"; • Can use input file object and >> to copy data from file to variables inFile >> partNum; inFile >> qtyInStock >> qtyOnOrder;

  46. Close the File • Close the file • Use the close member function inFile.close(); outFile.close(); • Don’t wait for operating system to close files at program end • May be limit on number of open files • May be buffered output data waiting to be sent to a file that could be lost

  47. Chapter 3: Expressions and Interactivity Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda

  48. String Operators = Assigns a value to a string string words; words = "Tasty "; + Joins two strings together string s1 = "hot", s2 = "dog"; string food = s1 + s2; // food = "hotdog" += Concatenates a string onto the end of another one words += food;// words now = "Tasty hotdog"

  49. 3.5 Overflow and Underflow Occurs when assigning a value that is too large (overflow) or too small (underflow) to be held in a variable The variable contains a value that is ‘wrapped around’ the set of possible values

  50. Overflow Example // Create a short int initialized to // the largest value it can hold short int num = 32767; cout << num; // Displays 32767 num = num + 1; cout << num; // Displays -32768

More Related