200 likes | 302 Views
C++ for Java Programmers. Chapter 10 Input/Output. Introduction. Two competing I/O systems in C++. Standard I/O Library, stdio Stream I/O Library, iostream Never use both Libraries in the same program. The stdio Library. “Inherited” from the C language. Widely known and available.
E N D
C++ for Java Programmers Chapter 10 Input/Output C++ for Java Programmers
Introduction • Two competing I/O systems in C++. • Standard I/O Library,stdio • Stream I/O Library, iostream • Never use both Libraries in the same program. C++ for Java Programmers
The stdio Library • “Inherited” from the C language. • Widely known and available. • Based on stable and well-exercised libraries. • Not as extendable or adaptable as the newer Stream I/O Library. • For developing new programs, the Stream I/O Library is preferred. C++ for Java Programmers
Examples of stdio # include <cstdio> // or stdio.h int c = getchar(); // read a single input character putchar('x'); // print a single character char * text = "please enter your name:";puts(text); // print the text stringchar buffer[120];gets(buffer); // read a line of input FILE * fp = fopen("mydata.dat", "r");if (fp == NULL)puts("file cannot be opened"); fputc('z', fp); // write character to fpint c = fgetc(fp); // read character from fpchar * msg = "unrecoverable program error";fputs(msg, stderr); // write message to standard error output C++ for Java Programmers
Formatted Output • The printf facility works only for formatted primitive values, such as integers and floats. • Always verify that formatting commands match the argument types; compiler does not check C++ for Java Programmers
Examples of Formatted Output %d integer decimal value %o integer printed as octal %x integer printed as hexadecimal %c integer printed as character %u unsigned integer decimal value %f floating point value %g floating point value %s null terminated string value %% percent sign C++ for Java Programmers
Exmples of printf int i = 3; int j = 7; double d = i / (double) j; printf("the value of %d over %d is %g", i, j, d); char * fileName = ...; if (fopen(fileName, "r") == null) fprintf(stderr,"Cannot open file %s\n", fileName); char buffer[180]; sprintf(buffer, "the value is %d\n", sum); double d = 23.5; printf("the value is %d\n", d); // error -- float printed as int scanf("%d %f", &i, &f); // read an int, then a float C++ for Java Programmers
Problems with printf • Works fine for built-in types, but • Not easily expanded for new user-defined types • Compiler cannot check formatting/argument agreement • So, is there another way?? C++ for Java Programmers
The Stream I/O Facility • Whenever possible use the Stream I/O Library rather than the Standard I/O Library. • Uses the ability to overload function names in C++. • Better possibilities for extendability as well as improved error detection. C++ for Java Programmers
Stream output overloads << op ostream & operator << (ostream & out, const int value) { // print signed integer values on a stream unsigned int usvalue; if (value < 0) // print leading minus sign { out << '-'; usvalue = -value; } else // print non-negative number usvalue = value; out << usvalue; return out; } C++ for Java Programmers
Printing int as recursive fun inline char digitCharacter(unsigned int value) { return value + '0'; } ostream & operator << (ostream & out, const unsigned int value) { // print unsigned integer values on a stream if (value < 10) out << digitCharacter(value); else { out << (value / 10); // recursive call out << digitCharacter(value % 10); } return out; } C++ for Java Programmers
Complex output built in parts # include <iostream> cout << "n " << n << " m " << m << " average " << (n+m)/2.0 << '\n'; C++ for Java Programmers
Easy to extend to new types ostream & operator << (ostream & out, const rational & value) { // print representation of rational number on an output stream out << value.numerator() << '/' << value.denominator(); return out; } rational frac(3,4); cout << "fraction of " << 3 << " and " << 4 << " is “ << frac << endl; C++ for Java Programmers
I/O Manipulators • A manipulator is used to change features of the I/O system. ostream & endl (ostream & out) {out << '\n'; // write the end of line character out.fflush(); // then flush the buffer return out; // then return the buffer } ostream & operator << (ostream & out, ostream & (*fun)(ostream &)) {return fun (out); // simply execute function } C++ for Java Programmers
Stream Input • Stream input ignores white space. cin >> intval; while (cin >> intval) { // process intval ...}// reach this point on end of input... • Visualize >> and << as arrows • Input operator, >> x : points data into x • Output operator, << x : copies data out of x C++ for Java Programmers
File Streams • A file stream is a stream that reads from or writes to a file. • Must include the header file # include <fstream> • fstream header file includes the iostream header, so not necessary to include both. • The class ifstream and ofstream are used to create streams that are attached to input and output files. C++ for Java Programmers
Conversion Operators • A conversion operator changes a file stream into a boolean value, whereby the value indicates the success or failure of the file opening operation. char fileName = "outfile.dat"; ofstream ofd(fileName); // create file for output if (! ofd) { cerr << " cannot open file " << fileName } else { ofd << "first line in file" ... } • File operations in C++ throw far fewer exceptions than do in Java. C++ for Java Programmers
Test your Understanding • What is the include file for the standard I/O library? • How do you use the function printf? • What are some problems with the printf function? C++ for Java Programmers
Test your Understanding • What is the error? double pi = 3.14159; printf(“Pi is %d\n”, pi); C++ for Java Programmers
Test your Understanding • What is the include file for the stream I/O facility? • What operator is used for stream output? • Why is this approach more easily extensible than the printf approach? C++ for Java Programmers