Absolute C++ (phần 14) docx

40 391 0
Absolute C++ (phần 14) docx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

520 Streams and File I/O Output streams have other member functions besides precision and setf. One very commonly used formatting function is width. For example, consider the following call to width made by the stream cout: cout << "Start Now"; cout.width(4); cout << 7 << endl; Display 12.5 Formatting Flags for setf FLAG MEANING OF SETTING THE FLAG DEFAULT ios::fixed Floating-point numbers are not written in e-notation. (Setting this flag automatically unsets the flag ios::scientific.) Not set ios::scientific Floating-point numbers are written in e-notation. (Setting this flag automatically unsets the flag ios::fixed.) If neither ios::fixed nor ios::scientific is set, then the system decides how to output each number. Not set ios::showpoint A decimal point and trailing zeros are always shown for floating- point numbers. If it is not set, a number with all zeros after the decimal point might be output without the decimal point and following zeros. Not set ios::showpos A plus sign is output before positive integer values. Not set ios::right If this flag is set and some field-width value is given with a call to the member function width, then the next item output will be at the right end of the space specified by width. In other words, any extra blanks are placed before the item output. (Setting this flag automatically unsets the flag ios::left.) Set ios::left If this flag is set and some field-width value is given with a call to the member function width, then the next item output will be at the left end of the space specified by width. In other words, any extra blanks are placed after the item output. (Setting this flag automatically unsets the flag ios::right.) Not set ios::dec Integers are output in decimal (base 10) notation. Set ios::oct Integers are output in octal (base 8) notation. Not set ios::hex Integers are output in hexadecimal (base 16) notation. Not set ios::uppercase An uppercase E is used instead of a lowercase e in scientific nota- tion for floating-point numbers. Hexadecimal numbers are output using uppercase letters. Not set ios::showbase Shows the base of an output number (leading O for octal, leading Ox for hexadecimal). Not set width Tools for Stream I/O 521 This code will cause the following line to appear on the screen: Start Now 7 This output has exactly three spaces between the letter ’w’ and the number 7. The width function tells the stream how many spaces to use when giving an item as output. In this case the number 7 occupies only one space and width is set to use four spaces, so three of the spaces are blank. If the output requires more space than you specified in the argument to width, then as much additional space as is needed will be used. The entire item is always output, no matter what argument you give to width. Any flag that is set may be unset. To unset a flag, use the function unsetf. For exam- ple, the following will cause your program to stop including plus signs on positive inte- gers that are output to the stream cout: cout.unsetf(ios::showpos); When a flag is set, it remains set until it is unset. The effect of a call to precision stays in effect until the precision is reset. However, the member function width behaves differently. A call to width applies only to the next item that is output. If you want to output 12 numbers, using four spaces to output each number, then you must call width 12 times. If this becomes a nuisance, you may prefer to use the manipulator setw that is described in the next subsection. ■ MANIPULATORS A manipulator is a function that is called in a nontraditional way. Manipulators are placed after the insertion operator <<, just as if the manipulator function call were an item to be output. Like traditional functions, manipulators may or may not have argu- ments. We have already seen one manipulator, endl. This subsection discusses two manipulators called setw and setprecision. The manipulator setw and the member function width (which you have already seen) do exactly the same thing. You call the setw manipulator by writing it after the T HE C LASS ios The class ios has a number of important defined constants, such as ios::app (used to indicate that you are appending to a file) and the flags listed in Display 12.5. The class ios is defined in libraries for output streams, such as <iostream> and <fstream>. One way to make the class ios and hence all these constants (all these flags) available to your code is the following: #include <iostream> //or #include <fstream> or both using std::ios; unsetf manipulator setw 522 Streams and File I/O insertion operator, <<, as if it were to be sent to the output stream, and this in turn calls the member function width. For example, the following will output the numbers 10, 20, and 30, using the field widths specified: cout << "Start" << setw(4) << 10 << setw(4) << 20 << setw(6) << 30; The preceding statement will produce the following output: Start 10 20 30 (There are two spaces before the 10, two spaces before the 20, and four spaces before the 30.) Like the member function width, a call to setw applies only to the next item output, but it is easier to include multiple calls to setw than it is to make multiple calls to width. The manipulator setprecision does the same thing as the member function preci- sion (which you have already seen). However, a call to setprecision is written after the insertion operator, <<, in a manner similar to how you call the setw manipulator. For example, the following will output the numbers listed using the number of digits after the decimal point that are indicated by the call to setprecision: cout.setf(ios::fixed); cout.setf(ios::showpoint); cout << "$" << setprecision(2) << 10.3 << endl << "$" << 20.5 << endl; The above statement will produce the following output: $10.30 $20.50 When you set the number of digits after the decimal point using the manipulator set- precision , then just as was the case with the member function precision, the setting stays in effect until you reset it to some other number by another call to either setpre- cision or precision. To use either of the manipulators setw or setprecision, you must include the fol- lowing directive in your program: #include <iomanip> using namespace std; or must use one of the other ways of specifying the names and namespace, such as the following: #include <iomanip> using std::setw; using std::setprecision; setprecision <iomanip> Tools for Stream I/O 523 ■ SAVING FLAG SETTINGS A function should not have unwanted or unexpected side effects. For example, a func- tion to output amounts of money might contain cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); After the function invocation ends, these settings will still be in effect. If you do not want such side effects, you can save and restore the original settings. The function precision has been overloaded so that with no arguments it returns the current precision setting so the setting can later be restored. The flags set with setf are easy to save and restore. The member function flags is overloaded to provide a way to save and then restore the flag settings. The member function cout.flags( ) returns a value of type long that codes all the flag settings. The flags can be reset by using this long value as an argument to cout.flags. These tech- niques work the same for file output streams as they do for cout. For example, a function to save and restore these settings could be structured as follows: void outputStuff(ofstream& outStream) { int precisionSetting = outStream.precision( ); long flagSettings = outStream.flags( ); outStream.setf(ios::fixed); outStream.setf(ios::showpoint); outStream.precision(2); Do whatever you want here. outStream.precision(precisionSetting); outStream.flags(flagSettings); } Another way to restore settings is cout.setf(0, ios::floatfield); An invocation of the member function setf with these arguments will restore the default setf settings. Note that these are the default values, not necessarily the settings before the last time they were changed. Also note that the default setting values are implementation-dependent. Finally, note that this does not reset precision settings or any settings that are not set with setf. 524 Streams and File I/O Self-Test Exercises ■ MORE OUTPUT STREAM MEMBER FUNCTIONS Display 12.6 summarizes some of the formatting member functions for the class ostream and some of the manipulators. Remember that to use the manipulators you need the following (or something similar): #include <iomanip> using namespace std; 8. What output will be produced when the following lines are executed? cout << "*"; cout.width(5); cout << 123 << "*" << 123 << "*" << endl; cout << "*" << setw(5) << 123 << "*" << 123 << "*" << endl; 9. What output will be produced when the following lines are executed? cout << "*" << setw(5) << 123; cout.setf(ios::left); cout << "*" << setw(5) << 123; Display 12.6 Formatting Tools for the Class ostream FUNCTION DESCRIPTION CORRESPONDING MANIPULATOR setf( ios_Flag ) Sets flags as described in Display 12.5 setiosflags( ios_Flag ) unsetf( ios_Flag ) Unsets flag resetiosflags( ios_Flag ) setf(0, ios::floatfield) Restores default flag settings None precision(int) Sets precision for floating-point number output setprecision(int) precision( ) Returns the current precision setting None width(int) Sets the output field width; applies only to the next item output setw(int) fill(char) Specifies the fill character when the out- put field is larger than the value output; the default is a blank setfill(char) Tools for Stream I/O 525 Example cout.setf(ios::right); cout << "*" << setw(5) << 123 << "*" << endl; 10. What output will be produced when the following lines are executed? cout << "*" << setw(5) << 123 << "*" << 123 << "*" << endl; cout.setf(ios::showpos); cout << "*" << setw(5) << 123 << "*" << 123 << "*" << endl; cout.unsetf(ios::showpos); cout.setf(ios::left); cout << "*" << setw(5) << 123 << "*" << setw(5) << 123 << "*" << endl; 11. What output will be sent to the file stuff.txt when the following lines are executed? ofstream fout; fout.open("stuff.txt"); fout << "*" << setw(5) << 123 << "*" << 123 << "*" << endl; fout.setf(ios::showpos); fout << "*" << setw(5) << 123 << "*" << 123 << "*" << endl; fout.unsetf(ios::showpos); fout.setf(ios::left); fout << "*" << setw(5) << 123 << "*" << setw(5) << 123 << "*" << endl; 12. What output will be produced when the following line is executed (assuming the line is embedded in a complete and correct program with the proper include and using directives)? cout << "*" << setw(3) << 12345 << "*" << endl; C LEANING U P A F ILE F ORMAT The program in Display 12.7 takes its input from the file rawdata.txt and writes its output, in a neat format, both to the screen and to the file neat.txt. The program copies numbers from the file rawdata.txt to the file neat.txt, but it uses formatting instructions to write them in a neat way. The numbers are written one per line in a field of width 12, which means that each number is preceded by enough blanks so that the blanks plus the number occupy 12 spaces. The numbers are written in ordinary notation; that is, they are not written in e-notation. Each number is written with five digits after the decimal point and with a plus or minus sign. The program uses a function, named makeNeat, that has formal parameters for the input-file stream and the output-file stream. 526 Streams and File I/O Display 12.7 Formatting Output (part 1 of 2) 1 //Reads all the numbers in the file rawdata.dat and writes the numbers 2 //to the screen and to the file neat.dat in a neatly formatted way. 3 #include <iostream> 4 #include <fstream> 5 #include<cstdlib> 6 #include <iomanip> 7 using std::ifstream; 8 using std::ofstream; 9 using std::cout; 10 using std::endl; 11 using std::ios; 12 using std::setw; 13 void makeNeat(ifstream& messyFile, ofstream& neatFile, 14 int numberAfterDecimalpoint, int fieldWidth); 15 //Precondition: The streams messyFile and neatFile have been connected to 16 //two different files. The file named messyFile contains only floating-point 17 //numbers. Postcondition: The numbers in the file connected to messyFile 18 //have been written to the screen and to the file connected to the stream 19 //neatFile. The numbers are written one per line, in fixed-point notation 20 //(that is, not in e-notation), with numberAfterDecimalpoint digits after 21 //the decimal point; each number is preceded by a plus or minus sign and each 22 //number is in a field of width fieldWidth. (This function does not close 23 //the file.) 24 int main( ) 25 { 26 ifstream fin; 27 ofstream fout; 28 fin.open("rawdata.txt"); 29 if (fin.fail( )) 30 { 31 cout << "Input file opening failed.\n"; 32 exit(1); 33 } 34 35 fout.open("neat.txt"); 36 if (fout.fail( )) 37 { 38 cout << "Output file opening failed.\n"; 39 exit(1); 40 } 41 makeNeat(fin, fout, 5, 12); 42 fin.close( ); 43 fout.close( ); Needed for setw Stream parameters must be call-by-reference parameters. Tools for Stream I/O 527 Display 12.7 Formatting Output (part 2 of 2) 44 cout << "End of program.\n"; 45 return 0; 46 } 47 //Uses <iostream>, <fstream>, and <iomanip>: 48 void makeNeat(ifstream& messyFile, ofstream& neatFile, 49 int numberAfterDecimalpoint, int fieldWidth) 50 { 51 neatFile.setf(ios::fixed); 52 neatFile.setf(ios::showpoint); 53 neatFile.setf(ios::showpos); 54 neatFile.precision(numberAfterDecimalpoint); 55 cout.setf(ios::fixed); 56 cout.setf(ios::showpoint); 57 cout.setf(ios::showpos); 58 cout.precision(numberAfterDecimalpoint); 59 double next; 60 while (messyFile >> next) 61 { 62 cout << setw(fieldWidth) << next << endl; 63 neatFile << setw(fieldWidth) << next << endl; 64 } 65 } setf and precision behave the same for a file output stream as they do for cout. Satisfied if there is a next number to read Works the same for file output streams as it does for cout neat.txt (After program is run) +10.37000 -9.89897 +2.31300 -8.95000 +15.00000 +7.33333 +92.87650 -123.75684 S CREEN O UTPUT +10.37000 -9.89897 +2.31300 -8.95000 +15.00000 +7.33333 +92.87650 -123.75684 End of program. rawdata.txt (Not changed by program) 10.37 -9.89897 2.313 -8.950 15.0 7.33333 92.8765 -1.237568432e2 528 Streams and File I/O Example E DITING A T EXT F ILE The program discussed here is a very simple example of text editing applied to files. This program can be used to automatically generate C++ advertising material from existing C advertising mate- rial (in a rather simplistic way). The program takes its input from a file that contains advertising copy that says good things about C and writes similar advertising copy about C++ in another file. The file that contains the C advertising copy is called cad.txt, and the new file that receives the C++ advertising copy is called cppad.txt. The program is shown in Display 12.8. The program simply reads every character in the file cad.txt and copies the characters to the file cppad.txt. Every character is copied unchanged, except that when the uppercase letter ’C’ is read from the input file, the program writes the string "C++" to the output file. This program assumes that whenever the letter ’C’ occurs in the input file, it names the C programming lan- guage; so this change is exactly what is needed to produce the updated advertising copy. Notice that the line breaks are preserved when the program reads characters from the input file and writes the characters to the output file. The newline character ’\n’ is treated just like any other character. It is read from the input file with the member function get, and it is written to the output file using the insertion operator, <<. We must use the member function get to read the input (rather than the extraction operator, >>) because we want to read whitespace. Stream Hierarchies: A Preview of Inheritance One very useful way to organize classes is by means of the “derived from” relationship. When we say that one class is derived from another class we mean that the derived class was obtained from the other class by adding features. For example, the class of input- file streams is derived from the class of all input streams by adding additional member functions such as open and close. The stream cin belongs to the class of all input streams, but does not belong to the class of input-file streams because cin has no mem- ber functions named open and close. This section introduces the notion of a derived class as a way to think about and organize the predefined stream classes. (Chapter 14 shows how to use the idea of a derived class to define classes of your own.) ■ INHERITANCE AMONG STREAM CLASSES Both the predefined stream cin and an input-file stream are input streams. So in some sense they are similar. For example, you can use the extraction operator, >>, with either kind of stream. On the other hand, an input-file stream can be connected to a file using the member function open, but the stream cin has no member function named open. An input-file stream is a similar but different kind of stream than cin. An input-file stream is of type ifstream. The object cin is an object of the class istream (spelled without the ’f’). The classes ifstream and istream are different but closely related types. The class ifstream is a derived class of the class istream. Let’s see what that means. 12.3 Stream Hierarchies: A Preview of Inheritance 529 Display 12.8 Editing a File of Text (part 1 of 2) 1 //Program to create a file called cplusad.txt that is identical to the file 2 //cad.txt except that all occurrences of ’C’ are replaced by "C++". Assumes 3 //that the uppercase letter ’C’ does not occur in cad.txt except as the 4 //name of the C programming language. 5 #include <fstream> 6 #include <iostream> 7 #include <cstdlib> 8 using std::ifstream; 9 using std::ofstream; 10 using std::cout; 11 void addPlusPlus(ifstream& inStream, ofstream& outStream); 12 //Precondition: inStream has been connected to an input file with open. 13 //outStream has been connected to an output file with open. 14 //Postcondition: The contents of the file connected to inStream have been 15 //copied into the file connected to outStream, but with each ’C’ replaced 16 //by "C++". (The files are not closed by this function.) 17 int main( ) 18 { 19 ifstream fin; 20 ofstream fout; 21 cout << "Begin editing files.\n"; 22 fin.open("cad.txt"); 23 if (fin.fail( )) 24 { 25 cout << "Input file opening failed.\n"; 26 exit(1); 27 } 28 fout.open("cppad.txt"); 29 if (fout.fail( )) 30 { 31 cout << "Output file opening failed.\n"; 32 exit(1); 33 } 34 addPlusPlus(fin, fout); [...]... (next == ’C’) outStream and each (incorrect) occurrence... complete tutorial on random access to files, but will let you know the name of the main stream class used and the important issues you will encounter If you want to be able to both read and write to a file in C++, you use the stream class fstream that is defined in the library The definition of fstream is placed in the std namespace Details about opening a file and connecting it to a stream in the class... subtask is a smaller version of the original task to be accomplished, you can solve the original task using a recursive function We begin with a simple example to illustrate this technique RECURSION In C++ a function definition may contain a call to the function being defined In such cases the function is said to be recursive Example VERTICAL NUMBERS Display 13.1 contains a demonstration program for... digits long: { writeVertical(the number n with the last digit removed); cout . no language as versatile as C, and C is fun to use. C++ is one of the world’s most modern programming languages. There is no language as versatile as C++, and C++ is fun to use. cad.txt (Not changed by. perhaps you are given the job of writing such a pack- age in C++, or perhaps you are just curious about how such things are done in C++. C++ does provide for random access to files so that your program. writes similar advertising copy about C++ in another file. The file that contains the C advertising copy is called cad.txt, and the new file that receives the C++ advertising copy is called cppad.txt.

Ngày đăng: 07/07/2014, 05:20

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan