Tài liệu Bài giảng C++ Programming: From Problem Analysis to Program Design, Fourth Edition - Chapter 3: Input/Output: C++ Programming: From Problem Analysis to Program Design, Fourth EditionChapter 3: Input/OutputC++ Programming: From Problem Analysis to Program Design, Fourth Edition2ObjectivesIn this chapter, you will:Learn what a stream is and examine input and output streamsExplore how to read data from the standard input deviceLearn how to use predefined functions in a programExplore how to use the input stream functions get, ignore, putback, and peekC++ Programming: From Problem Analysis to Program Design, Fourth Edition3Objectives (continued)Become familiar with input failureLearn how to write data to the standard output deviceDiscover how to use manipulators in a program to format outputLearn how to perform input and output operations with the string data typeBecome familiar with file input and outputC++ Programming: From Problem Analysis to Program Design, Fourth Edition4I/O Streams and Standard I/O DevicesI/O: sequence of bytes (stream of bytes) from source to destinationBytes are usually ...
48 trang |
Chia sẻ: honghanh66 | Lượt xem: 987 | Lượt tải: 0
Bạn đang xem trước 20 trang mẫu tài liệu Bài giảng C++ Programming: From Problem Analysis to Program Design, Fourth Edition - Chapter 3: Input/Output, để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên
C++ Programming: From Problem Analysis to Program Design, Fourth EditionChapter 3: Input/OutputC++ Programming: From Problem Analysis to Program Design, Fourth Edition2ObjectivesIn this chapter, you will:Learn what a stream is and examine input and output streamsExplore how to read data from the standard input deviceLearn how to use predefined functions in a programExplore how to use the input stream functions get, ignore, putback, and peekC++ Programming: From Problem Analysis to Program Design, Fourth Edition3Objectives (continued)Become familiar with input failureLearn how to write data to the standard output deviceDiscover how to use manipulators in a program to format outputLearn how to perform input and output operations with the string data typeBecome familiar with file input and outputC++ Programming: From Problem Analysis to Program Design, Fourth Edition4I/O Streams and Standard I/O DevicesI/O: sequence of bytes (stream of bytes) from source to destinationBytes are usually characters, unless program requires other types of information Stream: sequence of characters from source to destinationInput stream: sequence of characters from an input device to the computerOutput stream: sequence of characters from the computer to an output deviceC++ Programming: From Problem Analysis to Program Design, Fourth Edition5I/O Streams and Standard I/O Devices (continued)Use iostream header file to extract (receive) data from keyboard and send output to the screenContains definitions of two data types:istream - input streamostream - output streamHas two variables:cin - stands for common inputcout - stands for common outputC++ Programming: From Problem Analysis to Program Design, Fourth Edition6I/O Streams and Standard I/O Devices (continued)To use cin and cout, the preprocessor directive #include must be usedVariable declaration is similar to: istream cin;ostream cout;Input stream variables: type istream Output stream variables: type ostreamC++ Programming: From Problem Analysis to Program Design, Fourth Edition7cin and the Extraction Operator >>The syntax of an input statement using cin and the extraction operator >> is: The extraction operator >> is binaryLeft-side operand is an input stream variableExample: cinRight-side operand is a variableC++ Programming: From Problem Analysis to Program Design, Fourth Edition8cin and the Extraction Operator >> (continued)No difference between a single cin with multiple variables and multiple cin statements with one variableWhen scanning, >> skips all whitespaceBlanks 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 2C++ Programming: From Problem Analysis to Program Design, Fourth Edition9cin and the Extraction Operator >> (continued)Entering a char value into an int or double variable causes serious errors, called input failureC++ Programming: From Problem Analysis to Program Design, Fourth Edition10cin and the Extraction Operator >> (continued)When reading data into a char variable>> skips leading whitespace, finds and stores only the next characterReading stops after a single characterTo 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 characterC++ Programming: From Problem Analysis to Program Design, Fourth Edition11cin and the Extraction Operator >> (continued)C++ Programming: From Problem Analysis to Program Design, Fourth Edition13Using Predefined Functions in a ProgramFunction (subprogram): set of instructions When activated, it accomplishes a task main executes when a program is runOther functions execute only when called C++ includes a wealth of functionsPredefined functions are organized as a collection of libraries called header filesC++ Programming: From Problem Analysis to Program Design, Fourth Edition14Using 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 fileYou also need to know:Function nameNumber of parameters requiredType of each parameterWhat the function is going to doC++ Programming: From Problem Analysis to Program Design, Fourth Edition15Using Predefined Functions in a Program (continued)To use pow (power), include cmathTwo numeric parametersSyntax: pow(x,y) = xyx and y are the arguments or parametersIn pow(2,3), the parameters are 2 and 3C++ Programming: From Problem Analysis to Program Design, Fourth Edition17Using Predefined Functions in a Program (continued)Sample Run:Line 1: 2 to the power of 6 = 64Line 4: 12.5 to the power of 3 = 1953.13Line 5: Square root of 24 = 4.89898Line 7: u = 181.019Line 9: Length of str = 20C++ Programming: From Problem Analysis to Program Design, Fourth Edition18cin and the get FunctionThe get functionInputs next character (including whitespace)Stores in memory location indicated by its argumentThe syntax of cin and the get function: varCharIs a char variableIs the argument (parameter) of the functionC++ Programming: From Problem Analysis to Program Design, Fourth Edition19cin and the ignore Functionignore: discards a portion of the inputThe syntax to use the function ignore is: intExp is an integer expression chExp is a char expressionIf intExp is a value m, the statement says to ignore the next m characters or all characters until the character specified by chExpC++ Programming: From Problem Analysis to Program Design, Fourth Edition20putback and peek Functionsputback functionPlaces previous character extracted by the get function from an input stream back to that stream peek functionReturns next character from the input streamDoes not remove the character from that streamC++ Programming: From Problem Analysis to Program Design, Fourth Edition21putback and peek Functions (continued)The syntax for putback: istreamVar: an input stream variable (cin)ch is a char variableThe syntax for peek: istreamVar: an input stream variable (cin)ch is a char variableC++ Programming: From Problem Analysis to Program Design, Fourth Edition22The Dot Notation Between I/O Stream Variables and I/O FunctionsIn the statement cin.get(ch); cin and get are two separate identifiers separated by a dotDot separates the input stream variable name from the member, or function, nameIn C++, dot is the member access operatorC++ Programming: From Problem Analysis to Program Design, Fourth Edition23Input FailureThings can go wrong during executionIf input data does not match corresponding variables, program may run into problemsTrying to read a letter into an int or double variable will result in an input failureIf an error occurs when reading dataInput stream enters the fail stateC++ Programming: From Problem Analysis to Program Design, Fourth Edition24The clear FunctionOnce 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 resultsThe clear function restores input stream to a working state C++ Programming: From Problem Analysis to Program Design, Fourth Edition25Output and Formatting OutputSyntax of cout when used with C++ Programming: From Problem Analysis to Program Design, Fourth Edition27fixed Manipulatorfixed outputs floating-point numbers in a fixed decimal formatExample: cout > operator can read a string into a variable of the data type stringExtraction operatorSkips any leading whitespace characters and reading stops at a whitespace character The function getlineReads until end of the current lineC++ Programming: From Problem Analysis to Program Design, Fourth Edition35File Input/OutputFile: area in secondary storage to hold infoFile I/O is a five-step process Include fstream headerDeclare file stream variablesAssociate the file stream variables with the input/output sourcesUse the file stream variables with >>, <<, or other input/output functionsClose the filesC++ Programming: From Problem Analysis to Program Design, Fourth Edition36Programming Example: Movie Ticket Sale and Donation to CharityA theater owner agrees to donate a portion of gross ticket sales to a charityThe program will prompt the user to input:Movie nameAdult ticket priceChild ticket priceNumber of adult tickets soldNumber of child tickets soldPercentage of gross amount to be donatedC++ Programming: From Problem Analysis to Program Design, Fourth Edition37Programming Example: I/OInputs: movie name, adult and child ticket price, # adult and child tickets sold, and percentage of the gross to be donatedProgram output:-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*Movie Name: ....................... Journey to MarsNumber of Tickets Sold: ........... 2650Gross Amount: ..................... $ 9150.00Percentage of Gross Amount Donated: 10.00%Amount Donated: ................... $ 915.00Net Sale: ......................... $ 8235.00C++ Programming: From Problem Analysis to Program Design, Fourth Edition38Programming Example: Problem AnalysisThe program needs to:Get the movie nameGet the price of an adult ticket priceGet the price of a child ticket priceGet the number of adult tickets soldGet the number of child tickets soldC++ Programming: From Problem Analysis to Program Design, Fourth Edition39Programming 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 resultsC++ Programming: From Problem Analysis to Program Design, Fourth Edition40Programming Example: Variablesstring movieName;double adultTicketPrice;double childTicketPrice;int noOfAdultTicketsSold;int noOfChildTicketsSold;double percentDonation;double grossAmount;double amountDonated;double netSaleAmount;C++ Programming: From Problem Analysis to Program Design, Fourth Edition41Programming Example: Formatting OutputFirst column is left-justifiedWhen printing a value in the first column, use leftNumbers in second column are right-justifiedBefore printing a value in the second column, use rightUse setfill to fill the empty space between the first and second columns with dotsC++ Programming: From Problem Analysis to Program Design, Fourth Edition42Programming 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 numberBefore printing the dollar signUse setfill to set the filling character to blankC++ Programming: From Problem Analysis to Program Design, Fourth Edition43Programming Example: Main AlgorithmDeclare variablesSet the output of the floating-point to:Two decimal placesFixed Decimal point and trailing zerosPrompt the user to enter a movie nameInput movie name using getline because it might contain spacesPrompt user for price of an adult ticketC++ Programming: From Problem Analysis to Program Design, Fourth Edition44Programming Example: Main Algorithm (continued)Input price of an adult ticketPrompt user for price of a child ticketInput price of a child ticketPrompt user for the number of adult tickets soldInput number of adult tickets soldPrompt user for number of child tickets soldInput the number of child tickets soldC++ Programming: From Problem Analysis to Program Design, Fourth Edition45Programming Example: Main Algorithm (continued)Prompt user for percentage of the gross amount donatedInput percentage of the gross amount donatedCalculate the gross amountCalculate the amount donatedCalculate the net sale amountOutput the resultsC++ Programming: From Problem Analysis to Program Design, Fourth Edition46SummaryStream: infinite sequence of characters from a source to a destinationInput stream: from a source to a computerOutput stream: from a computer to a destinationcin: common inputcout: common outputTo use cin and cout, include iostream headerC++ Programming: From Problem Analysis to Program Design, Fourth Edition47Summary (continued)get reads data character-by-characterputback puts last character retrieved by get back to the input streamignore skips data in a linepeek returns next character from input stream, but does not remove itAttempting to read invalid data into a variable causes the input stream to enter the fail stateC++ Programming: From Problem Analysis to Program Design, Fourth Edition48Summary (continued)The manipulators setprecision, fixed, showpoint, setw, setfill, left, and right can be used for formatting outputInclude iomanip for the manipulators setprecision, setw, and setfillFile: area in secondary storage to hold infoHeader fstream contains the definitions of ifstream and ofstream
Các file đính kèm theo tài liệu này:
- 9781423902096_ppt_ch03_2403.ppt