DOC PREVIEW
Yale CPSC 427 - Chapter 3: C++ I/O for the C Programmer
School name Yale University
Pages 16

This preview shows page 1-2-3-4-5 out of 16 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 16 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 16 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 16 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 16 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 16 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 16 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

3 C++ I/O for the C Programmer3.1 Familiar Things in a New Language3.2 Include Files3.3 Streams and Files3.3.1 Common Stream Errors, Misconceptions, and Problems3.4 Input3.5 Output3.6 I/O and File Handling Demonstration3.7 End of File and Error Handling3.7.1 Using the command line.3.7.2 Reading Lines of Text3.7.3 EOF and error handling with numeric input.3.8 Assorted short notes.Chapter 3: C++ I/O for the C ProgrammerHow to learn C++:Try to put into practice what you already know, and in so doing you will in good timediscover the hidden things which you now inquire about.— Henry Van Dyke, American clergyman, educator, and author.3.1 Familiar Things in a New LanguageIn C, scanf() and printf() are only defined for the built-in types and the programmer must supply a formatfield specifier for each variable read or printed. If the field specifier does not agree with the type of the variable,garbage will result.In contrast, C++ supports a generic I/O facility called “C++ stream I/O”. Input and output conversionare controlled by the declared type of the I/O variables: you write the same thing to output a double or a stringas you write for an integer, but the results are different. This makes casual input and output easier. However,controlling field width, justification, and output precision is a pain in C++. The commands to do these jobsare wordy, non-intuitive, and cannot be combined on the same line with ordinary output commands. You canalways use C formatted I/O in C++; you may prefer to do so if you want easy format control. Both systemscan be, and often are, used in the same program. However, in this class, please use only C++ I/O.This section is for people who know the stdio library in C and want convert their knowledge to C++ (orvice-versa). Several I/O tasks are listed; for each the C solution is given first, followed by the C++ solution.Code fragments are given to illustrate each item. Boring but accurate short programs that use the commandsin context are also supplied.3.2 Include FilesC: #include <stdio.h>C++:• #include <iostream> for interactive I/O.• #include <iomanip> for format control.• #include <fstream> for file I/O.• #include <sstream> for strings that emulate streams.• using namespace std; to bring the names of included library facilities into your working namespace.3.3 Streams and FilesA stream is an object created by a program to allow it to access a file, socket, or some other source or destinationfor data.Predeclared streams:• C: stdin, stdout, stderr• C++: cin, cout, cerr, clog• The C++ streams cin and cout share buffers with the corresponding C streams. The streams stderrand cerr are unbuffered. The new stream, clog is used for logging transactions.1920 CHAPTER 3. C++ I/O FOR THE C PROGRAMMERStream handling. When a stream is opened, a data structure is created that contains the stream buffer,several status flags, and all the other information necessary to manage the stream.• C:typedef FILE* stream; /* Or include tools.h. */stream fin, fout;fout = fopen( "myfile.out", "w" ); /* Open stream for writing. */fin = fopen( "myfile.in", "r" ); /* Open stream for reading. */if (fin == NULL) /* Test for unsuccessful open. */if (feof( fin )) /* Test for end of file. */• C++: Stream classes are built into C++; a typedef is not needed. There are several stream classes thatform a class hierarchy whose root is the class ios. This class defines flags and functions that are commonto all stream classes. Below that are the two classes whose names are used most often: istream for inputand ostream for output. The predefined stream cin is an istream; cout, cerr, and clog are ostreams.These are all sequential streams–data is either read or written in strict sequential order. In contrast, theiostreams permit random-access input and output, such as a database would require. Below all three ofthese main stream classes are file-based streams and strings that emulate streams.iosistreamostreamofstreamifstream fstreamios_basestreambufiostreamostringstreamistringstream stringstreamFigure 3.1: The stream type hierarchy.Each class in the stream hierarchy is a variety of the class above it. When you call a function that isdefined for a class high in the tree, you can use an argument of any class that is below that. For example,if fin is an ifstream (which is used for an input file) you can call any function defined for class istreamor class ios with fin as an argument.ofstream fout ( "myfile.out" ); // Open stream for writing.ifstream fin ( "myfile.in" ); // Open stream for reading.fin.open( "myfile.in" ); // Alternate way to open a stream.fin.close(); // Close a stream--not usually necessary.if (!fin) fatal(...); // Test for unsuccessful open.if (fin.eof()) break; // Test for end of file.if (fin.good()) ... // Test for successful read operation.if (fin.fail()) ... // Test for hardware or conversion error.The stream declaration and open statement are combined in one line. The second declaration shown aboveis supposed to work, and works on my system. If the file does not exist, it is not created, and the ifstatement on the fifth line is used to handle the error. According to one student, though, this does notwork properly in Visual C++ 4.1. If the file does not exist, this command creates it. To avoid creation ofan empty file, he must open the file with the flag ios::nocreate, thus:ifstream in ( "parts.in", ios::nocreate | ios::in ); // For Visual C++ ?if (!in) fatal( "Could not open file parts.in" );Closing streams. In both languages, streams are closed automatically when the program terminates.To close a stream prior to the end of the program:– In C: fclose( fin );– In C++: fin.close();3.4. INPUT 213.3.1 Common Stream Errors, Misconceptions, and ProblemsStream ties: cout is tied to cin, that is, whenever the cout buffer is non-empty and input is called foron cin, cout is automatically flushed. This is also true in C: stdout is tied to stdin. Both languageswere designed this way so that you could display an input prompt without adding a newline to flush thebuffer, and permit the input to be on the same line as the prompt.Flushing streams. The standard fflush() function in C applies only to output streams. Somestudents have the belief that you can also flush a C input stream; this might be true in some nonstandardimplementation, but it is not true according to the C standard.In C++, flush is technically a manipulator, not a function, but it also applies only to


View Full Document

Yale CPSC 427 - Chapter 3: C++ I/O for the C Programmer

Download Chapter 3: C++ I/O for the C Programmer
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Chapter 3: C++ I/O for the C Programmer and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Chapter 3: C++ I/O for the C Programmer 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?