320 likes | 490 Views
CHAPTER 3 INPUT/OUTPUT. 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
E N D
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, fill, putback, and peek • 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
I/O STREAMS AND STANDARD I/O DEVICES • To use cin and cout every C++ program must use the preprocessor directive #include <iostream> cin>>payRate; Extraction Operator (>>) cin>>payRate>>hoursWorked; • When scanning for the next input, >> skips all leading whitespaces until the data has read. • Whitespace characters consist of blanks and certain nonprintable characters, such as tabs and the newline character.
Example 3-1 int a,b; double z; char ch,ch1,ch2; Statement Input Value Stored in Memory 2 cin>>ch; AB ch='A', 'B' is held for later input 4 cin>>a; 46.35 a=46, .35 is held for later input 6 cin>>z; 39 z=39.0 9 cin>>a>>ch>>z; 57 A 26.9 a=57, ch='A', z=26.9 12 cin>>a>>ch>>z; 57A26.9 a=57, ch='A', z=26.9 15 cin>>a>>b>>z; 11 34 a=11, b=34, Computerwaits for the nextnumber
USING PREDEFINED FUNCTIONS IN A PROGRAM • A function, also called subprogram, is a set of instructions. • When a function is activated, that is, executed, it accomplishes something. • The function main is executed automatically when we execute a program. • Other functions are executed only when they are called. • The programming language C++ comes with a wealth of functions. • Predefined functions are organized as a collection of libraries, called header files. • pow(2,3)= 23 = 8and pow(4,0.5) = 40.5 = 2. • In pow(2,3), the parameters are 2 and 3. • An expression such as pow(2,3)is called a function call. • The header file cmathcontains the specification of the function pow.
cin and the get Function Consider the declaration: char ch1, ch2; int num; • 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: 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.
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. 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.
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.
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.
The peek and the putback Functions • The putback function places the previous character extracted by the get function from an input stream back to that stream. • The peek function returns the next character from the input stream but it does not remove the character from that stream, that is, the next input character would be the same. • The syntax to use the function peek is: char ch; ch = cin.peek(); cin.get(ch); cin.putback(ch);
INPUT FAILURE • If the input data did not match the corresponding variables, the program would run into problems. • Trying to read a letter into an int or double variable would result in an input failure. 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.
Once an input stream enters a fail state, all further I/O statements using that stream are ignored. • Unfortunately, the program quietly continues to execute with whatever values are stored in variables and produce incorrect results. The clear Function When an input stream enters the fail state, the system ignores all further I/O using that stream. You can use the stream function clear to restore the input stream to a working state. The syntax to use the function clear is: cin.clear();
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. • To use the manipulator, the program must include the header file iomanip. #include <iomanip>
setprecision The general form of setprecision is: setprecision(n) where n is the number of decimal places. cout<<setprecision(2); cout << setprecision(2) << num; will output all decimal numbers up to two decimal places until it is reset. • The following statement sets the output of floating-point numbers in a fixed decimal format on the standard output device: cout<<fixed;
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 a floating-point number in a fixed decimal format with the decimal point and trailing zeros on the standard output device: cout<<fixed<<showpoint;
C++ provides the manipulatorsetiosflags, to set the flags ios::fixed, ios::scientific, and ios::showpoint. • To use the manipulator setiosflags , the program must include the header file iomanip. cout<<setiosflags(ios::fixed); cout<<setiosflags(ios::showpoint); • You can specify more than one flag in the manipulator setiosflags by separating the flags with the symbol |. • The following statement sets both the flags ios::fixed and ios::showpoint on the standard output device: cout<<setiosflags(ios::fixed | ios::showpoint); • C++ provides the manipulator resetiosflags to reset the flags that was setted. cout << resetiosflags(ios::fixed)
setw setw(n) - output the value of the next expression in n columns. • The output is right justified. • If the number of specified columns is less than the number of columns required by the output, then the output is automatically expanded to the required number of columns. • Unlike setprecision, which controls the output of all floating-point numbers until it is reset, setw controls the output of only the next expression. • To use the manipulator setw, the program must include the header file iomanip. int num = 25; cout << setw(4) << num; --25
ADDITIONAL OUTPUT FORMATTING TOOLS fill and setfill • In the manipulatorsetw if the number of columns specified are more than the number of columns required by the expression, the output of the expression is right justified and the unused columns to the left are filled with spaces. • The output stream variables, such as cout, can use the function fill and/or the manipulator setfill to fill the unused columns with a character other than the space. The syntax to use the function fill is: cout<<setfill('#'); sets the filling character to '#'. int num = 25; cout << setw(4) << setfill(‘#’)<< num; ##25
The leftand rightManipulators • To left-justify the output, you use the manipulator left. • The following statement sets the output to be left-justified on the standard output device: int num = 25; cout << left; cout << setw(4) << num; 25-- cout << setw(4) << setfill(‘#’)<< num; 25## • The following statement sets the output to be right-justified on the standard output device: cout << right; cout << setw(4) << num; ##25
The flush Function • Both the manipulator endl and the newline escape sequence \n position the cursor at the beginning of the next line on the output device. • When a program sends output to an output device, the output first goes to the buffer in the computer. • Whenever the buffer becomes full, the output is sent to the output device. • As soon as the manipulator endl is encountered, the output from the buffer is sent to the output device immediately, even if the buffer is not full. • The manipulator endl positions the cursor at the beginning of the next line on an output device and helps clear the buffer. • It is quite possible that sometimes you may not see the entire output because when the program terminates, the buffer at that time may not be full.
In C++, you can use the function flush to clear the buffer, even if the buffer is not full. • In contrast to the manipulator endl, the function flush does not move the cursor to the beginning of the next line. • Just like endl, the function flush can be used as a manipulator. In such a case, flush is used in an output statement without the parentheses. For example, the following statement sends the output from the buffer to the standard output device: cout<<"Enter an integer: "<<flush;
You can disable the manipulator by using the stream member function . • Member function comes with the Dot operator cout.unsetf(ios::fixed); cout.unsetf(ios::left); cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout.width(4); cout.fill('*'); cout.flush();
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. Alice Wonderland name Alice
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'. string name; getline(cin,name); Alice Wonderland name • 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. Alice Wonderland
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?"
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.
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. inData.open("A:prog.dat");//open input file outData.open("A:prog.out");//open output file
I/O with input and output files • 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.
Close File inData.close(); outData.close();
#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; }