Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3: Input/Output

Similar presentations


Presentation on theme: "Chapter 3: Input/Output"— Presentation transcript:

1 Chapter 3: Input/Output
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 3: Input/Output

2 Objectives In this chapter, you will:
Learn what a stream is and examine input and output streams Explore how to read data from the standard input device Learn how to use predefined functions in a program Explore how to use the input stream functions get, ignore, putback, and peek C++ Programming: Program Design Including Data Structures, Fourth Edition

3 Objectives (continued)
Become familiar with input failure Learn how to write data to the standard output device Discover how to use manipulators in a program to format output Learn how to perform input and output operations with the string data type Become familiar with file input and output C++ Programming: Program Design Including Data Structures, Fourth Edition

4 I/O Streams and Standard I/O Devices
I/O: sequence of bytes (stream of bytes) from source to destination Bytes are usually characters, unless program requires other types of information Stream: sequence of characters from source to destination Input stream: sequence of characters from an input device to the computer Output stream: sequence of characters from the computer to an output device C++ Programming: Program Design Including Data Structures, Fourth Edition

5 I/O Streams and Standard I/O Devices (continued)
Use iostream header file to extract (receive) data from keyboard and send output to the screen Contains definitions of two data types: istream - input stream ostream - output stream Has two variables: cin - stands for common input cout - stands for common output C++ Programming: Program Design Including Data Structures, Fourth Edition

6 I/O Streams and Standard I/O Devices (continued)
To use cin and cout, the preprocessor directive #include <iostream> must be used Variable declaration is similar to: istream cin; ostream cout; Input stream variables: type istream Output stream variables: type ostream C++ Programming: Program Design Including Data Structures, Fourth Edition

7 cin and the Extraction Operator >>
The syntax of an input statement using cin and the extraction operator >> is: The extraction operator >> is binary Left-side operand is an input stream variable Example: cin Right-side operand is a variable C++ Programming: Program Design Including Data Structures, Fourth Edition

8 cin and the Extraction Operator >> (continued)
No difference between a single cin with multiple variables and multiple cin statements with one variable When scanning, >> skips all whitespace Blanks and certain nonprintable characters >> distinguishes between character 2 and number 2 by the right-side operand of >> If type char or int (or double), the 2 is treated as a character or as a number 2 C++ Programming: Program Design Including Data Structures, Fourth Edition

9 cin and the Extraction Operator >> (continued)
Entering a char value into an int or double variable causes serious errors, called input failure C++ Programming: Program Design Including Data Structures, Fourth Edition

10 cin and the Extraction Operator >> (continued)
When reading data into a char variable >> skips leading whitespace, finds and stores only the next character Reading stops after a single character To read data into an int or double variable >> skips leading whitespace, reads + or - sign (if any), reads the digits (including decimal) Reading stops on whitespace non-digit character C++ Programming: Program Design Including Data Structures, Fourth Edition

11 cin and the Extraction Operator >> (continued)
C++ Programming: Program Design Including Data Structures, Fourth Edition

12

13 Using Predefined Functions in a Program
Function (subprogram): set of instructions When activated, it accomplishes a task main executes when a program is run Other functions execute only when called C++ includes a wealth of functions Predefined functions are organized as a collection of libraries called header files C++ Programming: Program Design Including Data Structures, Fourth Edition

14 Using Predefined Functions in a Program (continued)
Header file may contain several functions To use a predefined function, you need the name of the appropriate header file You also need to know: Function name Number of parameters required Type of each parameter What the function is going to do C++ Programming: Program Design Including Data Structures, Fourth Edition

15 Using Predefined Functions in a Program (continued)
To use pow (power), include cmath Two numeric parameters Syntax: pow(x,y) = xy x and y are the arguments or parameters In pow(2,3), the parameters are 2 and 3 C++ Programming: Program Design Including Data Structures, Fourth Edition

16

17 Using Predefined Functions in a Program (continued)
Sample Run: Line 1: 2 to the power of 6 = 64 Line 4: 12.5 to the power of 3 = Line 5: Square root of 24 = Line 7: u = Line 9: Length of str = 20 C++ Programming: Program Design Including Data Structures, Fourth Edition

18 cin and the get Function
Inputs next character (including whitespace) Stores in memory location indicated by its argument The syntax of cin and the get function: varChar Is a char variable Is the argument (parameter) of the function C++ Programming: Program Design Including Data Structures, Fourth Edition

19 cin and the ignore Function
ignore: discards a portion of the input The syntax to use the function ignore is: intExp is an integer expression chExp is a char expression If intExp is a value m, the statement says to ignore the next m characters or all characters until the character specified by chExp C++ Programming: Program Design Including Data Structures, Fourth Edition

20 putback and peek Functions
putback function Places previous character extracted by the get function from an input stream back to that stream peek function Returns next character from the input stream Does not remove the character from that stream C++ Programming: Program Design Including Data Structures, Fourth Edition

21 putback and peek Functions (continued)
The syntax for putback: istreamVar: an input stream variable (cin) ch is a char variable The syntax for peek: C++ Programming: Program Design Including Data Structures, Fourth Edition

22 The Dot Notation Between I/O Stream Variables and I/O Functions
In the statement cin.get(ch); cin and get are two separate identifiers separated by a dot Dot separates the input stream variable name from the member, or function, name In C++, dot is the member access operator C++ Programming: Program Design Including Data Structures, Fourth Edition

23 Input Failure Things can go wrong during execution
If input data does not match corresponding variables, program may run into problems Trying to read a letter into an int or double variable will result in an input failure If an error occurs when reading data Input stream enters the fail state C++ Programming: Program Design Including Data Structures, Fourth Edition

24 The clear Function Once in a fail state, all further I/O statements using that stream are ignored The program continues to execute with whatever values are stored in variables This causes incorrect results The clear function restores input stream to a working state C++ Programming: Program Design Including Data Structures, Fourth Edition

25 Output and Formatting Output
Syntax of cout when used with << Expression is evaluated Value is printed Manipulator is used to format the output Example: endl C++ Programming: Program Design Including Data Structures, Fourth Edition

26 setprecision Manipulator
Syntax: Outputs decimal numbers with up to n decimal places Must include the header file iomanip: #include <iomanip> C++ Programming: Program Design Including Data Structures, Fourth Edition

27 fixed Manipulator fixed outputs floating-point numbers in a fixed decimal format Example: cout << fixed; Disable by using the stream member function unsetf Example: cout.unsetf(ios::fixed); The manipulator scientific is used to output floating-point numbers in scientific format C++ Programming: Program Design Including Data Structures, Fourth Edition

28 showpoint Manipulator
showpoint forces output to show the decimal point and trailing zeros Examples: cout << showpoint; cout << fixed << showpoint; C++ Programming: Program Design Including Data Structures, Fourth Edition

29 setw Outputs the value of an expression in specific columns
cout << setw(5) << x << endl; If number of columns exceeds the number of columns required by the expression Output of the expression is right-justified Unused columns to the left are filled with spaces Must include the header file iomanip C++ Programming: Program Design Including Data Structures, Fourth Edition

30 3.8 Formatting Output Can control how output displays for numeric and string data size position number of digits Requires iomanip header file Chapter 1 Starting Out with C++: Early Objects 5/e Slide 30 © 2006 Pearson Education. All Rights Reserved

31 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. Chapter 1 Starting Out with C++: Early Objects 5/e Slide 31 © 2006 Pearson Education. All Rights Reserved

32 #include <iostream> using namespace std; int main() {
int num1 = 2897, num2 = 5, num3 = 837, num4 = 34, num5 = 7, num6 = 1623, num7 = 390, num8 = 3456, num9 = 12; cout << num1 << " " << num2 << " " << num3 << endl; cout << num4 << " " << num5 << " " << num6 << endl; cout << num7 << " " << num8 << " " << num9 << endl; return 0; } Chapter 1 Starting Out with C++: Early Objects 5/e Slide 32 © 2006 Pearson Education. All Rights Reserved

33 #include <iostream>
#include <iomanip> // Header file needed to use setw using namespace std; int main() { int num1 = 2897, num2 = 5, num3 = 837, num4 = 34, num5 = 7, num6 = 1623, num7 = 390, num8 = 3456, num9 = 12; cout << setw(6) << num1 << setw(6) << num2 << setw(6) << num3 << endl; cout << setw(6) << num4 << setw(6) << num5 << setw(6) << num6 << endl; cout << setw(6) << num7 << setw(6) << num8 << setw(6) << num9 << endl; return 0; } Chapter 1 Starting Out with C++: Early Objects 5/e Slide 33 © 2006 Pearson Education. All Rights Reserved

34 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 for floating-point values. left, right: left-, right justification of value Chapter 1 Starting Out with C++: Early Objects 5/e Slide 34 © 2006 Pearson Education. All Rights Reserved

35 Manipulator Examples const float e = 2.718;
float price = 25.0; Displays cout << setw(8) << e << endl; ^^^2.718 cout << left << setw(8) << e << endl; ^^^ cout << setprecision(2); cout << e << endl; cout << fixed << e << endl; cout << setw(6) << price; ^18.00 See pr3-15.cpp through pr3-21.cpp Chapter 1 Starting Out with C++: Early Objects 5/e Slide 35 © 2006 Pearson Education. All Rights Reserved

36 // This program demonstrates how the setprecision manipulator
// affects the way a floating-point value is displayed. #include <iostream> #include <iomanip> using namespace std; int main() { double quotient, number1 = , number2 = 26.91; quotient = number1 / number2; cout << quotient << endl; cout << setprecision(5) << quotient << endl; cout << setprecision(4) << quotient << endl; cout << setprecision(3) << quotient << endl; cout << setprecision(2) << quotient << endl; cout << setprecision(1) << quotient << endl; return 0; } Chapter 1 Starting Out with C++: Early Objects 5/e Slide 36 © 2006 Pearson Education. All Rights Reserved

37 // This program illustrates the how the fixed, showpoint, and
// setprecision manipulators operate when used together. #include <iostream> #include <iomanip> // Needed to use stream manipulators using namespace std; int main() { double amount1 = * .075; //amount1 is set to 9.375 double amount2 = * .06; //amount2 is set to 7.5 double amount3 = * .20; //amount3 is set to 25.0 cout << fixed << showpoint << setprecision(2); cout << setw(5) << amount1 << endl; cout << setw(5) << amount2 << endl; cout << setw(5) << amount3 << endl; return 0; } Chapter 1 Starting Out with C++: Early Objects 5/e Slide 37 © 2006 Pearson Education. All Rights Reserved

38 3.11 More Mathematical Library Functions
These require cmath header file Take double arguments and return a double Commonly used functions abs Absolute value sin Sine cos Cosine tan Tangent sqrt Square root log Natural (e) log See pr3-31.cpp Chapter 1 Starting Out with C++: Early Objects 5/e Slide 38 © 2006 Pearson Education. All Rights Reserved

39 More Mathematical Library Functions
These require cstdlib header file rand Returns a random number between 0 and the largest int the computer holds With the same seed, will yield same sequence of numbers each time program is run srand(x) Initializes random number generator with unsigned int x See pr3-32.cpp Chapter 1 Starting Out with C++: Early Objects 5/e Slide 39 © 2006 Pearson Education. All Rights Reserved

40 // This program demonstrates random numbers. #include <iostream>
#include <cstdlib> using namespace std; int main() { unsigned seed; cout << "Enter a seed value: "; cin >> seed; srand (seed); // Call srand to set a "seed" before // any random numbers can be generated cout << rand () << endl; // Now generate and print 3 random numbers cout << rand () << endl; return 0; } Chapter 1 Starting Out with C++: Early Objects 5/e Slide 40 © 2006 Pearson Education. All Rights Reserved

41 #include <iostream> #include <cstdlib>
using namespace std; int main() { int i, temp, count[2]; count[0]=count[1]=0; for (i=0; i<1000; i++){ temp=rand()%2; count[temp]++; cout<< temp<<' '; if ((i%30)==29) cout<<endl; }; cout<<"Num. of 0="<<count[0]<<",Num. of 1="<<count[1]; return 0; } Chapter 1 Starting Out with C++: Early Objects 5/e Slide 41 © 2006 Pearson Education. All Rights Reserved

42 Additional Output Formatting Tools
Additional formatting tools that give you more control over your output: setfill manipulator left and right manipulators unsetf manipulator C++ Programming: Program Design Including Data Structures, Fourth Edition

43 setfill Manipulator Output stream variables can use setfill to fill unused columns with a character Example: cout << setfill('#'); C++ Programming: Program Design Including Data Structures, Fourth Edition

44 left and right Manipulators
left: left-justifies the output Disable left by using unsetf right: right-justifies the output C++ Programming: Program Design Including Data Structures, Fourth Edition

45 Types of Manipulators Two types of manipulators:
With parameters Without parameters Parameterized: require iomanip header setprecision, setw, and setfill Nonparameterized: require iostream header endl, fixed, showpoint, left, and flush C++ Programming: Program Design Including Data Structures, Fourth Edition

46 Input/Output and the string Type
An input stream variable (cin) and >> operator can read a string into a variable of the data type string Extraction operator Skips any leading whitespace characters and reading stops at a whitespace character The function getline Reads until end of the current line C++ Programming: Program Design Including Data Structures, Fourth Edition

47 File Input/Output File: area in secondary storage to hold info
File I/O is a five-step process Include fstream header Declare file stream variables Associate the file stream variables with the input/output sources Use the file stream variables with >>, <<, or other input/output functions Close the files C++ Programming: Program Design Including Data Structures, Fourth Edition

48 3.12 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 They allow data to be retained between program runs Chapter 1 Starting Out with C++: Early Objects 5/e Slide 48 © 2006 Pearson Education. All Rights Reserved

49 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; Chapter 1 Starting Out with C++: Early Objects 5/e Slide 49 © 2006 Pearson Education. All Rights Reserved

50 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 Chapter 1 Starting Out with C++: Early Objects 5/e Slide 50 © 2006 Pearson Education. All Rights Reserved

51 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; See pr3-33.cpp. pr3-34.cpp, and pr3-35.cpp Chapter 1 Starting Out with C++: Early Objects 5/e Slide 51 © 2006 Pearson Education. All Rights Reserved

52 #include <iostream>
// This program uses the << operator to write information to a file. #include <iostream> #include <fstream> // Needed to use files using namespace std; int main() { ofstream outputFile; outputFile.open("demofile.txt"); cout << "Now writing information to the file.\n"; outputFile << "Bach\n"; outputFile << "Beethoven\n"; outputFile << "Mozart\n"; outputFile.close(); cout << "Done.\n"; return 0; } Chapter 1 Starting Out with C++: Early Objects 5/e Slide 52 © 2006 Pearson Education. All Rights Reserved

53 #include <iostream>
// This program uses the >> operator to read information from a file. #include <iostream> #include <fstream> // Needed to use files #include <string> using namespace std; int main() { ifstream inFile; string name; inFile.open("demofile.txt"); cout << "Reading information from the file.\n\n"; inFile >> name; // Read name 1 from the file cout << name << endl; // Display name 1 inFile >> name; // Read name 2 from the file cout << name << endl; // Display name 2 inFile >> name; // Read name 3 from the file cout << name << endl; // Display name 3 inFile.close(); // Close the file cout << "\nDone.\n"; return 0; } Chapter 1 Starting Out with C++: Early Objects 5/e Slide 53 © 2006 Pearson Education. All Rights Reserved

54 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 Chapter 1 Starting Out with C++: Early Objects 5/e Slide 54 © 2006 Pearson Education. All Rights Reserved

55 Problem Assume that the file “data.txt” contains the two numbers: 23
14 Write a program that reads the two numbers from “data.txt” and writes their sum into the file “result.txt”. Chapter 1 Starting Out with C++: Early Objects 5/e Slide 55 © 2006 Pearson Education. All Rights Reserved

56 #include <iostream>
#include <fstream> // Needed to use files using namespace std; int main() { ifstream inputFile; ofstream outputFile; int num1, num2; outputFile.open("result.txt"); inputFile.open("data.txt"); inputFile >>num1; inputFile >>num2; outputFile <<num1+num2; inputFile.close(); outputFile.close(); return 0; } Chapter 1 Starting Out with C++: Early Objects 5/e Slide 56 © 2006 Pearson Education. All Rights Reserved

57 Programming Example: Movie Ticket Sale and Donation to Charity
A theater owner agrees to donate a portion of gross ticket sales to a charity The program will prompt the user to input: Movie name Adult ticket price Child ticket price Number of adult tickets sold Number of child tickets sold Percentage of gross amount to be donated C++ Programming: Program Design Including Data Structures, Fourth Edition

58 Programming Example: I/O
Inputs: movie name, adult and child ticket price, # adult and child tickets sold, and percentage of the gross to be donated Program output: -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* Movie Name: Journey to Mars Number of Tickets Sold: Gross Amount: $ Percentage of Gross Amount Donated: % Amount Donated: $ Net Sale: $ C++ Programming: Program Design Including Data Structures, Fourth Edition

59 Programming Example: Problem Analysis
The program needs to: Get the movie name Get the price of an adult ticket price Get the price of a child ticket price Get the number of adult tickets sold Get the number of child tickets sold C++ Programming: Program Design Including Data Structures, Fourth Edition

60 Programming Example: Problem Analysis (continued)
Calculate the gross amount grossAmount = adultTicketPrice * noOfAdultTicketsSold + childTicketPrice * noOfChildTicketsSold; Calculate the amount donated to the charity amountDonated = grossAmount * percentDonation / 100; Calculate the net sale amount netSale = grossAmount – amountDonated; Output the results C++ Programming: Program Design Including Data Structures, Fourth Edition

61 Programming Example: Variables
string movieName; double adultTicketPrice; double childTicketPrice; int noOfAdultTicketsSold; int noOfChildTicketsSold; double percentDonation; double grossAmount; double amountDonated; double netSaleAmount; C++ Programming: Program Design Including Data Structures, Fourth Edition

62 Programming Example: Formatting Output
First column is left-justified When printing a value in the first column, use left Numbers in second column are right-justified Before printing a value in the second column, use right Use setfill to fill the empty space between the first and second columns with dots C++ Programming: Program Design Including Data Structures, Fourth Edition

63 Programming Example: Formatting Output (continued)
In the lines showing gross amount, amount donated, and net sale amount Use blanks to fill space between the $ sign and the number Before printing the dollar sign Use setfill to set the filling character to blank C++ Programming: Program Design Including Data Structures, Fourth Edition

64 Programming Example: Main Algorithm
Declare variables Set the output of the floating-point to: Two decimal places Fixed Decimal point and trailing zeros Prompt the user to enter a movie name Input movie name using getline because it might contain spaces Prompt user for price of an adult ticket C++ Programming: Program Design Including Data Structures, Fourth Edition

65 Programming Example: Main Algorithm (continued)
Input price of an adult ticket Prompt user for price of a child ticket Input price of a child ticket Prompt user for the number of adult tickets sold Input number of adult tickets sold Prompt user for number of child tickets sold Input the number of child tickets sold C++ Programming: Program Design Including Data Structures, Fourth Edition

66 Programming Example: Main Algorithm (continued)
Prompt user for percentage of the gross amount donated Input percentage of the gross amount donated Calculate the gross amount Calculate the amount donated Calculate the net sale amount Output the results C++ Programming: Program Design Including Data Structures, Fourth Edition

67 Summary Stream: infinite sequence of characters from a source to a destination Input stream: from a source to a computer Output stream: from a computer to a destination cin: common input cout: common output To use cin and cout, include iostream header C++ Programming: Program Design Including Data Structures, Fourth Edition

68 Summary (continued) get reads data character-by-character
putback puts last character retrieved by get back to the input stream ignore skips data in a line peek returns next character from input stream, but does not remove it Attempting to read invalid data into a variable causes the input stream to enter the fail state C++ Programming: Program Design Including Data Structures, Fourth Edition

69 Summary (continued) The manipulators setprecision, fixed, showpoint, setw, setfill, left, and right can be used for formatting output Include iomanip for the manipulators setprecision, setw, and setfill File: area in secondary storage to hold info Header fstream contains the definitions of ifstream and ofstream C++ Programming: Program Design Including Data Structures, Fourth Edition


Download ppt "Chapter 3: Input/Output"

Similar presentations


Ads by Google