Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Absolute C++ (4th Edition) part 52. KEY BENEFIT: C++ programming concepts and techniques are presented in a straightforward style using understandable language and code. KEY TOPICS: C++ Basics; Flow of Control; Function Basics; Parameters and Overloading; Arrays; Structures and Classes; Constructors; Operator Overloading, Friends, and References; Strings; Pointers and Dynamic Arrays; Separate Compilation and Namespaces; Streams and File I/O; Recursion; Inheritance; Polymorphism and Virtual Functions; Templates; Linked Data Structures; Exception Handling; Standard Template Library; Patterns and UML. MARKET: Useful for both beginning and intermediate C++ programmers. . | Tools for Stream I O 517 int count 0 next while ins next count cout next endl ins.close cout count The file list.txt contains the following three numbers and nothing more 1 2 3 7. Write the definition for a void function called toScreen. The function toScreen has one formal parameter called fileStream which is of type ifstream. The precondition and postcondition for the function are given below. Precondition The stream fileStream has been connected to a file with a call to the member function open. The file contains a list of integers and nothing else . Postcondition The numbers in the file connected to fileStream have been written to the screen one per line. This function does not close the file. 12.2 Tools for Stream I O You shall see them on a beautiful quarto page where a neat rivulet of text shall meander through a meadow of margin. Richard Brinsley Sheridan The School for Scandal FILE NAMES AS INPUT Thus far we have written the literal file names for our input and output files into the code of our programs. We did this by giving the file name as the argument to a call to the function open as in the following example inStream.openCinfile.txt You can instead read the file name in from the keyboard as illustrated by the following as a C-string char fileName 16 ifstream inStream 518 Streams and File I O cout Enter file name maximum of 15 characters n cin fileName inStream.open fileName Note that our code reads the file name as a C-string. The member function open takes an argument that is a C-string. You cannot use a string variable as an argument to open and there is no predefined type cast operator to convert from a string object as a string to a C-string. However as an alternative you can read the file name into a string vari- objed able and use the string member function c_str to produce the corresponding C-string value for open. The code would be as follows string fileName ifstream inStream cout Enter file name n cin fileName inStream.open fileName.c_str .