Presentation is loading. Please wait.

Presentation is loading. Please wait.

EGR 2261 Unit 3 Input/Output Read Malik, Chapter 3.

Similar presentations


Presentation on theme: "EGR 2261 Unit 3 Input/Output Read Malik, Chapter 3."— Presentation transcript:

1 EGR 2261 Unit 3 Input/Output Read Malik, Chapter 3.
Homework #3 and Lab #3 due next week. Quiz next week. Handouts: Quiz 2, Unit 3 practice sheets.

2 I/O Streams and Standard I/O Devices
I/O stands for input/output. An I/O Stream is a sequence of bytes traveling from a source to a destination. An input stream is a sequence of characters from an input device (such as the keyboard) to the computer. An output stream is a sequence of characters from the computer to an output device (such as the monitor). C++ Programming: From Problem Analysis to Program Design, Seventh Edition

3 I/O Streams and Standard I/O Devices (cont’d.)
You must include the iostream header file in any program that receives data from the keyboard or sends output to the screen. You do this with the preprocessor directive: #include <iostream> This header file declares two important variables: cin (which stands for “common input”) cout (which stands for “common output”) The data types of these variables are istream and ostream. These data types are defined in the iostream header file. Take a look inside C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\iostream. Note that in addition to declaring cin and cout, it also includes istream, which is a much longer file that in turn includes ostream, another much longer file that in turn includes other files….. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

4 cin and the Stream Extraction Operator >>
The stream extraction operator >> is the most common way of reading a value from the keyboard into a variable. Recall its syntax: The >> operator is a binary operator. The left-side operand must be an input stream variable, such as cin. The right-side operand must be a declared variable. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

5 cin and the Stream Extraction Operator >> (cont’d.)
Example of a cin statement using >>: int num1; cin >> num1; When this code executes, the program will wait until the user types a value and presses the Enter key. The program will then assign the user’s value to the variable named num1. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

6 cin and the Stream Extraction Operator >> (cont’d.)
There’s no difference between a single cin with multiple variables and multiple cin statements with one variable each. Example with one cin statement: cin >> num1 >> num2; Equivalent example with two cin statements: cin >> num1; cin >> num2; C++ Programming: From Problem Analysis to Program Design, Seventh Edition

7 The Extraction Operator and Various Data Types
The next few slides examine how the >> operator behaves when you use it to read values into variables of different data types (char, int, double, string, …). In all of these cases, the >> operator skips any leading whitespace. Recall that whitespace includes blanks, tabs, and line returns. As we’ll see later, there are other ways of reading in values that don’t skip leading whitespace.

8 The Extraction Operator and char data
When reading data into a char variable: >> skips leading whitespace, finds and stores only the next non-whitespace character. Reading stops after a single character. Example: suppose we’re executing this code: char myChar; cin >> myChar; If the user types hello there! followed by the Enter key, myChar will hold the value '+'. The remaining characters (23.47hello there!) are left sitting in the stream. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

9 The Extraction Operator and int data
When reading data into an int variable: >> skips leading whitespace, reads + or - sign (if any), reads the digits. Reading stops on any character that is not a digit. Example: suppose we’re executing this code: int myInt; cin >> myInt; If the user types hello there! followed by the Enter key, myInt will hold the value 23. The remaining characters (.47hello there!) are left sitting in the stream. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

10 The Extraction Operator and double data
When reading data into a double variable: >> skips leading whitespace, reads + or - sign (if any), reads the digits (including decimal point). Reading stops on any character that is not a digit or the decimal point or e or E or + or -. Example: suppose we’re executing this code: double myDouble; cin >> myDouble; If the user types hello there! followed by the Enter key, myDouble will hold the value The remaining characters (hello there!) are left sitting in the stream. Do practice question 1. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

11 The Extraction Operator and string data
When reading data into a string variable: >> skips leading whitespace. Reading stops at any whitespace character. Example: suppose we’re executing this code: string myString; cin >> myString; If the user types hello there! followed by the Enter key, myString will hold the value "+23.47hello". The remaining characters (there!) are left sitting in the stream. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

12 Input Failure An error called input failure can result if the user enters data of a different type from the type expected by the cin statement. Example: suppose we’re executing this code: int num1; cin >> num1; If the user types H followed by the Enter key, we’ll get an error since the user did not enter an integer value. As we’ll see later, C++ gives you tools to deal with this sort of error. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

13 Using Predefined Functions in a Program
Recall that a function is a named set of instructions that accomplishes some task. Recall also that the main function executes when a program is run. Other functions execute only when called. C++ includes a wealth of predefined functions. These predefined functions are organized into the header files (such as <iostream> and <string>) in the C++ Standard Library. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

14 Using Predefined Functions in a Program (cont’d.)
To use a predefined function, you must include the appropriate header file. You also need to know: The function’s name The number of parameters required The type of each parameter C++ Programming: From Problem Analysis to Program Design, Seventh Edition

15 Example of a Predefined Function: pow
The pow function raises a number to a power. To use pow, include the cmath header file: #include <cmath> The pow function takes two numeric parameters: Syntax: pow(x,y) This expression returns the value of xy. x and y are the parameters. In pow(2,3), the parameters are 2 and 3. So to square a variable named radius you could do either pow(radius,2) or radius*radius. Do practice question 2 parts a and b. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

16 Function-Call Syntax As we’ll see in the weeks ahead, the syntax used in calling pow on the previous slide is the same syntax that we’ll use in calling other functions. In particular, the syntax consists of the function’s name followed by zero or more parameters enclosed in parentheses and separated by commas. See the book’s Appendix F for other functions in cmath, such as sqrt(x). Demo square root.

17 These two are the most useful.
Some Predefined Functions in the iostream Header File The iostream header file defines many functions for processing keyboard input, including: getLine get ignore putback peek clear Depending on what you're trying to do, you might need to use these functions instead of (or in addition to) the extraction operator >>. These two are the most useful.

18 cin and the getLine Function
Recall that the >> operator can read a string into a variable of the string data type, but that reading skips leading whitespace and stops when it hits whitespace after any text. Alternatively, you can use the getline function. It does not skip leading whitespace, as >> does. And it reads until the end of the current line. It does not stop reading when it hits whitespace, as >> does. Syntax: where strVar is a string variable. getline(cin, strVar); C++ Programming: From Problem Analysis to Program Design, Seventh Edition

19 cin and the getLine Function (cont’d.)
Recalling an earlier example, suppose we’re executing this code: string myString; cin >> myString; If the user types hello there! followed by the Enter key, myString will hold the value "+23.47hello". But if instead the code is : string myString; getline(cin, myString); Now if the user types hello there! followed by the Enter key, myString will hold the value " hello there!". Demo using week03StringEntry.cpp Do all parts of practice question 3. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

20 cin and the get Function
Inputs the next character (including whitespace). Stores the character in the char variable named as the function's parameter. The syntax of the get function: where varChar is a char variable. Demo using week03Get.cpp Do practice question 6. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

21 cin and the get Function (cont’d.)
Recalling an earlier example, suppose we’re executing this code: char myChar; cin >> myChar; If the user types hello there! followed by the Enter key, myChar will hold the value '+'. But if instead the code is : char myChar; cin.get(myChar); Now if the user types hello there! followed by the Enter key, myChar will hold the value ' '. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

22 cin and the ignore Function
The ignore function discards a portion of the input stream. Syntax: intExp is an integer expression. chExp is a char expression. If intExp value's is m, the statement says to ignore the next m characters or all characters up to and including the character specified by chExp (whichever comes first). Do practice questions 7 and 8. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

23 cin and the ignore Function (cont’d.)
C++ Programming: From Problem Analysis to Program Design, Seventh Edition

24 cin.putback(varChar);
putback Function The putback function places the previous character extracted by the get function from an input stream back to that stream. Syntax: where varChar is a char variable. cin.putback(varChar); Demo using week03Putback.cpp C++ Programming: From Problem Analysis to Program Design, Seventh Edition

25 peek Function The peek function:
Tells you the next character in the input stream, but does not remove that character from the stream. Syntax: where varChar is a char variable. Demo using week03Peek.cpp varChar = cin.peek(); C++ Programming: From Problem Analysis to Program Design, Seventh Edition

26 The Dot Notation Between I/O Stream Variables and I/O Functions
In the statement cin.get(varChar); cin and get are two separate identifiers separated by a dot. The dot separates the input stream variable name from the member, or function, name. In C++, the dot is the member access operator. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

27 Input Failure Recall that the program may run into problems if input data does not match corresponding variables. Example: Trying to read a letter into an int or double variable results in an input failure and causes the input stream to enter the fail state. Once in the fail state, all further I/O statements using that stream are ignored. The program continues to execute with whatever values are stored in variables (possibly garbage values), causing incorrect results. Demo using week03InputFailState.cpp C++ Programming: From Problem Analysis to Program Design, Seventh Edition

28 The clear Function The clear function restores the input stream to a working state. Proper use of this function, along with the more general topic of responding to run-time errors, is an advanced topic that we will not study in detail. For this course, we’ll assume that users will enter values of the correct data types. cin.clear(); Can’t easily demo this. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

29 Output and Formatting Output
Syntax of cout and << expression is evaluated, and the value is printed. manipulator is used to format the output. Example of a manipulator: endl, which is an alternative to '\n' when you want to move to the next line on the display: cout << "Hello!\n"; cout << "Hello!" << endl; Do practice question 4. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

30 Some Manipulators that Affect Display of Floating-Point Numbers
The following manipulators let you control the display of floating-point numbers: fixed scientific setprecision(n) showpoint These manipulators have no effect on the display of integers, characters, strings, or other non-floating-point values.

31 fixed and scientific Manipulators
These are similar to modes on your calculator, causing subsequent floating-point numbers to be displayed either in a fixed decimal format or in scientific format. Example: cout << fixed; Example: cout << scientific; Demo using Ch3_scientificFixed.cpp (This is book’s Example 3-10). C++ Programming: From Problem Analysis to Program Design, Seventh Edition

32 setprecision Manipulator
Syntax: When used together with fixed or scientific, displays floating-point numbers to n decimal places. Example: cout << fixed << setprecision(4); To use setprecision, you must first include the header file iomanip: #include <iomanip> Demo what happens if you do cout << setprecision(3) before any of the couts in the previous program. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

33 showpoint Manipulator
showpoint forces output to show the decimal point and trailing zeros. Examples: cout << showpoint; cout << fixed << showpoint; cout << fixed << showpoint << setprecision(2); Demo using Ch3_setPrecisionFixed.cpp (This is book’s Example 3-11). Do practice question 5. Many of the book’s examples use this formatting. It’s a good general-purpose setting if you want floating-point numbers to be displayed to two decimal places. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

34 Some Other Manipulators
The following manipulators let you control the display of all values, not just floating-point numbers: setw(n) left and right setfill(ch) Use these when you want your program’s output to display in neatly aligned columns.

35 setw Manipulator The setw manipulator outputs an expression’s value using a specified number of characters. Example: To display a variable’s value in a 10- character-wide column (even if the value itself is only two or three characters), we can do: cout << setw(10) << x << endl; To use setw, you must include the header file iomanip. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

36 setw Manipulator: An Example
Run it (week03Setw.cpp)

37 left and right Manipulators
When you use setw and the specified number of characters exceeds the number of characters required by the expression, the expression is right-justified by default. The left manipulator left-justifies the output. The right manipulator right-justifies the output. cout << left; Demo by modifying previous program. cout << right; C++ Programming: From Problem Analysis to Program Design, Seventh Edition

38 cout << setfill(ch);
setfill Manipulator When you use setw and the specified number of characters exceeds the number of characters required by the expression, unused characters are filled with spaces by default. Use setfill to use some other character instead of spaces. Example: cout << setfill('#'); Demo by modifying previous program. cout << setfill(ch); C++ Programming: From Problem Analysis to Program Design, Seventh Edition

39 Which Header Files Do You Need?
Note that of the manipulators discussed above, some take a parameter, but others do not. You just have to include the <iostream> header to use the non-parameterized manipulators. These are: endl, fixed, scientific, showpoint, left, and right You must include the <iomanip> header to use the parameterized manipulators. These are: setprecision(n), setw(n), and setfill(ch) C++ Programming: From Problem Analysis to Program Design, Seventh Edition

40 Don’t Include Header Files That Your Program Does Not Need
We’ve seen that you must include header files (such as <iostream>, <iomanip>, <string>, <cmath>, and others) to use library functions. Including any of these files adds many lines of code to your program. Therefore, you should only include a header file if your program uses one or more functions from that file. I’ll check your programs to make sure that you are not including header files that you don’t need.

41 Debugging: Understanding Logic Errors and Debugging with cout statements
Syntax errors Reported by the compiler. Logic errors Typically not caught by the compiler. But you can spot them using cout statements: Temporarily insert one or more cout statements to display the values of variables. Identify and fix the problem. Remove the temporary cout statements. We’ll learn more powerful debugging techniques in future weeks. -Demo using Lab02Force to display all values used in the force equation; show what you get if you incorrectly enter K as 6.67*(10^-8). C++ Programming: From Problem Analysis to Program Design, Seventh Edition

42 File Input/Output A file is an area in secondary storage to hold data.
File I/O is a five-step process: Include the <fstream> header file. Declare file stream variables, which are of datatype ifstream or ofstream. Use the open command to associate the file stream variables with files on your disk, and open the files. Use the file stream variables with >>, <<, or input/output functions (such as get, getline, etc.). Close the files. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

43 Example Program Using An Input File
Demo with week03InputFile.cpp.

44 The Default Directory for Input and Output Files
When your program tries to use an input or output file, Visual Studio assumes the file is located in the same directory where your project’s .cpp file is stored. Example: for the Lab02Average project, this is the directory named C:\Users\nick.reeder\Documents\VisualStudio2015\Projects\Lab02Average\Lab02Average. You can change this default location, but I recommend that you leave it alone.

45 Creating an Input File For Use By Your Program
The previous program expects to find a file named myInputData.txt in the default directory. You must create this input file outside of Visual Studio before you run the program. In Windows Explorer, right-click inside the default folder and select New > Text Document. Then type text inside the file and save it with the correct filename (myInputData.txt).

46 Example Program Using An Output File
Demo with week03OutputFile.cpp.

47 File Input and File Output in the Same Program
Of the previous two example programs, The first one did file input and console output. The second one did keyboard input and file output. On Lab 3, the last two programs require you to do file input and file output in the same program, by combining techniques from the two example programs.


Download ppt "EGR 2261 Unit 3 Input/Output Read Malik, Chapter 3."

Similar presentations


Ads by Google