1 / 48

CHAPTER 3 INPUT/OUTPUT

CHAPTER 3 INPUT/OUTPUT. Input/Output Streams I/O is a sequence of bytes, called a stream of bytes , from the source to the destination. The bytes are usually characters, unless the program requires other types of information such as a graphic image or digital speech.

nituna
Download Presentation

CHAPTER 3 INPUT/OUTPUT

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 3INPUT/OUTPUT

  2. Input/Output Streams • I/O is a sequence of bytes, called a stream of bytes, from the source to the destination. • The bytes are usually characters, unless the program requires other types of information such as a graphic image or digital speech. • A stream is a sequence of characters from the source to the destination. Input Stream:A sequence of characters from an input device to the computer. Output Stream: A sequence of characters from the computer to an output device.

  3. I/O STREAMS AND STANDARD I/O DEVICES • To extract (that is, receive) data from keyboard and send output to the screen, every C++ program must use the header file iostream. • This header file, iostream, contains definitions of two data types, istream (input stream) and ostream (output stream). • The header file, iostream, contains the declaration of two variables, cin (stands for common input), pronounced see-in, and cout (stands for common output), pronounced see-out, and the declaration is similar to the following C++ statements: istream cin; ostream cout; • To use cin and cout every C++ program must use the preprocessor directive #include <iostream>

  4. Variables of the type istreamare called input stream variables. • Variables of the type ostreamare called output stream variables. • A stream variable is either an input stream variable or an output stream variable.

  5. cin and the Extraction Operator (>>) Consider the following C++ statement: cin>>payRate; If you type 15.50, the value stored in payRate after the execution of this statement is 15.50. • The extraction operator >> is binary.The left-hand operand is an input stream variable such as cin. The right-hand operand is a variable of a simple data type. • The purpose of an input statement is to read and store values in a memory location and only variables refer to memory locations, the items (that is, right hand operand in the case of the extraction operator, >>) must be a variable in an input statement.

  6. The syntax of an input statement using cinand the extraction operator >>is cin>>variable>>variable...;

  7. Every occurrence of >>extracts the next data item from the input stream. • You can read both payRateand hoursWorkedvia a single cinstatement by using the following code: cin>>payRate>>hoursWorked; • There is no difference between the preceding cinstatement and the following two cinstatements. cin>>payRate; cin>>hoursWorked; • When scanning for the next input, >> skips all whitespaces. • Whitespace characters consist of blanks and certain nonprintable characters, such as tabs and the newline character.

  8. Whether the input is 15.50 48.30 or 15.50 48.30 or 15.50 48.30 The input statement: cin>>payRate>>hoursWorked; would store 15.50in payRateand 48.30in hoursWorked.

  9. Suppose the input is 2. How does >> distinguish between character 2 and the number 2? • This is distinguished by the right hand operand of >>. • If the right hand operand, that is, variable, is of type char, input 2 is treated as character 2 (recall that in this case, the ASCII value of 2 will be stored). And if the right-hand operand is of the type int (or double), input 2 is treated as the number 2. • Now consider the input 25 and the statement: cin>>a; where a is a variable of some simple data type. • If a is of the data type char, then only the single character 2 will be stored in a. • If a is of the data type, say int, then 25 will be stored in a. • If a is of the type double, then the input 25 is converted to a decimal number with zero decimal part.

  10. Consider the statement cin>>a; where a is a variable of some simple data type.

  11. When reading data into a charvariable, after skipping any leading whitespace characters, the extraction operator >>finds and stores only the next character; reading stops after a single character. • To read data into an intor doublevariable, after skipping all leading whitespace characters and reading the plus or minus sign (if any), the extraction operator >>reads the digits of the number, including the decimal point for floating-point variables, and stops when it finds a whitespace character or a character other than a digit.

  12. Example 3-1 int a,b; double z; char ch,ch1,ch2; Statement Input Value Stored in Memory 1 cin>>ch; A ch='A' 2 cin>>ch; AB ch='A', 'B' is held for later input 3 cin>>a; 48 a=48 4 cin>>a; 46.35 a=46, .35 is held for later input 5 cin>>z; 74.35 z=74.35 6 cin>>z; 39 z=39.0 7 cin>>z>>a;65.78 38z=65.78, a=38 8 cin>>a>>b; 4 60 a=4, b=60 9 cin>>a>>ch>>z; 57 A 26.9 a=57, ch='A', z=26.9

  13. 16 cin>>a>>z; 46 32.4 68 a=46, z=32.4, 68 is held for later input 17 cin>>ch>>a; 256 ch='2', a=56 18 cin>>a>>ch; 256 a=256, computer waits for the input value for ch. 19 cin>>ch1>>ch2; A B ch1 = 'A', ch2 = 'B’ • During program execution, when entering character data such as letters, you do not enter the single quotes around the character. • Entering a charvalue into an intor doublevariable causes serious errors, called input failure.

  14. cin and the get Function Consider the declaration: char ch1, ch2; int num; and the input A 25 Now consider the statement: cin>>ch1>>ch2>>num; • When the computer executes this statement, A is stored in ch1, blank is skipped by >>, 2 is stored in ch2, and 5 is stored in num. • If we intended to store A in ch1, blank in ch2 and 25 in num? It is clear that we can not use the extraction operator >>.

  15. The get function inputs the very next character (including whitespaces) from the input stream and stores in the memory location indicated by its argument. • The syntax of cin together with the get function to read a character is: cin.get(varChar); where varChar is a char variable. • varChar is called the argument or parameter of the function. • The next input character is stored in varChar.

  16. Now, again, consider the input A 25 We can effectively use the get function as follows: cin.get(ch1); cin.get(ch2); cin>>num; to store A in ch1, blank in ch2, and 25 in num. The above set of statements is equivalent to the following: cin>>ch1; cin.get(ch2); cin>>num;

  17. cin and the ignore Function • To process partial data, say with in a line, we can effectively use the ignore function to discard some portion of the input. • The syntax to use the functionignore is: cin.ignore(intExp,chExp); where intExp is an integer expression yielding an integer value and chExp is acharexpression. • Suppose intExp yields a value, say m. This statement says, ignore the next m characters or until the character specified by chExp, whichever comes first.

  18. Consider the following statement: cin.ignore(100,'\n'); The execution of this statement will ignore the next 100 characters or until the newline character is found whichever comes first. The execution of the statement: cin.ignore(100,'A'); will result in ignoring the first 100 characters or until the character 'A' is found, whichever comes first.

  19. Example 3-2 int a,b; Suppose the input is: 25 67 89 43 72 12 78 34 Consider the statements: cin>>a; cin.ignore(100,'\n'); cin>>b; • The first statement cin>>a; stores 25 in a. • The second statement, cin.ignore(100,'\n');discards all of the remaining numbers in the first line. • The third statement cin>>b; stores 12 (from the next line) in b.

  20. Example 3-3 char ch1,ch2; Suppose the input is Hello there. My name is Mickey. Now consider the statements: cin>>ch1; cin.ignore(100,'.'); cin>>ch2; • The first statement cin>>ch1; stores 'H' in ch1. • The second statement, cin.ignore(100,'.' ); results in ignoring all characters until '.' (period). • The third statement cin>>ch2; stores 'M' (from the same line) in ch2.

  21. Consider the following statements int a, b, c; double x; If the input is W 54 then the statement cin>>a>>b; would result in an input failure because you are trying to input the character 'W' into the int variable a.

  22. OUTPUT AND FORMATTING OUTPUT Syntax of cout when used together with the insertion operator << is cout<<expression or manipulator <<expression or manipulator...; • expression is evaluated, its value is printed, and manipulator is used to format the output. • The simplest manipulator that you have used so far is endl, which is used to move the cursor to the beginning of the next line.

  23. setprecision The general form of setprecision is: setprecision(n) where n is the number of decimal places. The statement cout<<setprecision(2); will output all decimal numbers up to two decimal places until it is reset. To use the manipulator setprecision, the program must include the header file iomanip. #include <iomanip>

  24. fixed • To output floating-point numbers in a fixed decimal format, you use the manipulator fixed. • The following statement sets the output of floating-point numbers in a fixed decimal format on the standard output device: cout<<fixed; • After the preceding statement executes, all floating-point numbers are displayed in the fixed-decimal format until the manipulator fixed is disabled.

  25. You can disable the manipulator fixed by using the stream member function unsetf. • The following statement disables the manipulator fixed on the standard output device, you use: cout.unsetf(ios::fixed); • After the manipulator fixed is disabled, the output of the floating-point numbers return to their default settings. • The manipulator scientific is used to output floating-point numbers in scientific format.

  26. showpoint • If the decimal part of a decimal number is zero, then when you instruct the computer to output the decimal number in a fixed decimal format, the output may not show the decimal point and the decimal part. • To force the output to show the decimal point and trailing zeros, you use the manipulator showpoint. • The following statement sets the output of decimal numbers with a decimal point and trailing zeros on the standard input device: cout<<showpoint; • The following statement sets the output of a floating-point number in a fixed decimal format with the decimal point and trailing zeros on the standard output device: cout<<fixed<<showpoint;

  27. Example 3-7 //Example: setprecision, fixed, showpoint #include <iostream> #include <iomanip> using namespace std; int main() { double x,y,z; x = 15.674; //Line 1 y = 235.73; //Line 2 z = 9525.9864; //Line 3 cout<<fixed<<showpoint; //Line 4

  28. cout<<setprecision(2) <<"Line 5: setprecision(2)"<<endl; //Line 5 cout<<"Line 6: x = "<<x<<endl; //Line 6 cout<<"Line 7: y = "<<y<<endl; //Line 7 cout<<"Line 8: z = "<<z<<endl; //Line 8 cout<<setprecision(3) <<"Line 9: setprecision(3)"<<endl; //Line 9 cout<<"Line 10: x = "<<x<<endl; //Line 10 cout<<"Line 11: y = "<<y<<endl; //Line 11 cout<<"Line 12: z = "<<z<<endl; //Line 12

  29. cout<<setprecision(4) <<"Line 13: setprecision(4)"<<endl; //Line 13 cout<<"Line 14: x = "<<x<<endl; //Line 14 cout<<"Line 15: y = "<<y<<endl; //Line 15 cout<<"Line 16: z = "<<z<<endl; //Line 16 cout<<"Line 17: " <<setprecision(3)<<x<<" " <<setprecision(2)<<y<<" " <<setprecision(4)<<z<<endl; //Line 17 return 0; }

  30. Output: Line 5: setprecision(2) Line 6: x = 15.67 Line 7: y = 235.73 Line 8: z = 9525.99 Line 9: setprecision(3) Line 10: x = 15.674 Line 11: y = 235.730 Line 12: z = 9525.986 Line 13: setprecision(4) Line 14: x = 15.6740 Line 15: y = 235.7300 Line 16: z = 9525.9864 Line 17: 15.674 235.73 9525.9864

  31. Input/Output and the string Type • You can use an input stream variable, such as cin, and the extraction operator >> to read a string into a variable of the data type string. • If the input is the string "Shelly", the following code stores this input into the string variable name: string name; // declaration cin>>name; // input statement • The extraction operator skips any leading whitespace characters and that reading stops at a whitespace character. • You cannot use the extraction operator to read strings that contain blanks.

  32. If the input is Alice Wonderland the value of the variable name after the following statement executes is "Alice": cin>>name; • To read a string containing blanks, you can use the function getline . • The syntax to use the function getline is getline(istreamVar, strVar); where istreamVar is an input stream variable and strVar is a variable of the type string. The reading is delimited by the newline character, '\n'.

  33. The function getline reads until it reaches the end of the current line. • The newline character is also read but not stored in the string variable. • Consider the following statement: string myString; • If the input is 29 characters, bbbbHello there. How are you? where b represents a blank, after the statement getline(cin,myString); the value of myString is myString = " Hello there. How are you?"

  34. File Input/Output File: An area in secondary storage used to hold information. For file I/O, the following steps are necessary. 1. Include the header file fstream in the program. So the following statement is needed. #include <fstream> 2.Declare file (fstream) variables. For example the statements: ifstream inData; ofstream outData; declare the variable inData for input and outData for output. That is, inData is an input (file) stream variable and outData is an output (file) stream variable.

  35. 3. Open Files The general syntax for opening a file is fileStreamVariable.open(sourceName, fileOpeningMode); Here fileStreamVariable is a file stream variable, sourceName is the name of the input/output file, and fileOpeningMode specifies the mode in which the file is to be opened.

  36. Suppose declaration of Step 2. • Suppose that the input data is stored in a file called prog.dat on a floppy disk in drive A:. • Save the output in a file called prog.out on a floppy disk in drive A:. • The following statements associate inData with prog.dat and outData with prog.out. inData.open("A:prog.dat"); //open input file outData.open("A:prog.out"); //open output file

  37. Step 4: • Use the (file) stream variable together with >> or << or with other functions for input/Output. • The syntax for using >> or << with file variables is exactly similar to the syntax of cin and cout. • The statement inData>>payRate; reads the data from the file prog.dat and stores it in the variable payRate • The statement outData<<"The pay check is: "<<pay<<endl; stores the output line, which is: The pay check is:565.78, in the file prog.out. Here we are assuming that the pay was calculated as 565.78.

  38. Close File inData.close(); outData.close();

  39. #include <fstream> //Add additional header files you use using namespace std; int main() { //Declare file stream variables such as the following ifstream inData; ofstream outData; ... //Open files inData.open("A:prog.dat"); //open input file outData.open("A:prog.out"); // open output file //Code for data manipulation //Close files inData.close(); outData.close(); return 0; }

  40. PROGRAMMING EXAMPLE: STUDENT GRADE Write a program that reads a student ID followed by five test scores. The program should output the student ID, the five test scores, and the average test score. Output the average test score with two decimal places. Assume that the student ID is a character. The data to be read is stored in a file called test.txt, and the file is stored on a floppy disk in drive A:. The output should be stored in a file called testavg.out, and the output file should be stored on the floppy disk in drive A:. Input: A file containing the student ID and five test scores. Output: The student ID, five test scores and the average of the five test scores. The output is to be saved in a file.

  41. Problem Analysis and Algorithm Design To find the average of five test scores, first we add the five test scores and then divide the sum by 5. Now, the input data is in the form: student ID followed by five test scores. Therefore, we first read the student ID and then the five test scores. This discussion translates in the following algorithm: 1. Read student ID and the five test score. 2. Output student ID and five test scores. 3. Calculate the average. 4. Output the average. We will output the average test score in the fixed decimal format with two decimal places.

  42. Variables: ifstream inFile; //input file stream variable ofstream outFile; //output file stream variable int test1, test2, test3, test4, test5; // variables //to read five test scores double average; //variable to store average //test score char studentId; //variable to store //student ID

  43. Main Algorithm 1. Declare the variables. 2. Open the input file. 3. Open the output file. 4. To output the floating-point numbers in a fixed decimal format with a decimal point and trailing zeros, set the manipulators fixed and showpoint. Also, to output the floating-point numbers with two decimal places, set the precision to two decimal places. 5. Read the student ID. 6. Output the student ID. 7. Read the five test scores. 8. Output the five test scores. 9. Find the average test score. 10. Output the average test score. 11. Close the input and output files.

  44. //Program to calculate average test score. #include <iostream> #include <fstream> #include <iomanip> using namespace std; int main() { //Declare variables; Step 1 ifstream inFile; //input file stream variable ofstream outFile; //output file stream variable int test1, test2, test3, test4, test5; double average; char studentId;

  45. inFile.open("a:test.txt"); //Step 2 outFile.open("a:testavg.out"); //Step 3 outFile<<fixed<<showpoint; //Step 4 outFile<<setprecision(2); //Step 4 cout<<"Processing data"<<endl; inFile>>studentId; //Step 5 outFile<<"Student ID: "<<studentId <<endl; //Step 6 inFile>>test1>>test2>>test3 >>test4>>test5; //Step 7

  46. outFile<<"Test scores: "<<setw(4)<<test1 <<setw(4)<<test2<<setw(4)<<test3 <<setw(4)<<test4 <<setw(4)<<test5<<endl; //Step 8 average = static_cast<double>(test1+test2+test3+ test4+test5)/5.0; //Step 9 outFile<<"Average test score: "<<setw(6) <<average<<endl; //Step 10 inFile.close(); //Step 11 outFile.close(); //Step 11 return 0; }

  47. Sample Run: Input File: (contents of the file a:test.txt): T 87 89 65 37 98 Output File: (contents of the file a:testavg.out) Student ID: T Test scores: 87 89 65 37 98 Average test score: 75.20

More Related