1 / 19

Ch. 10 Input/Output

Ch. 10 Input/Output. Oregon State University Timothy Budd. Introduction. Two competing I/O systems in C++. Standard I/O Library, stdio Stream I/O Library, iostream Never use both Library in the same program. The stdio Library. Inherited from the C. Widely known and available.

Download Presentation

Ch. 10 Input/Output

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Ch. 10 Input/Output Oregon State University Timothy Budd Ch 10. Input/Output

  2. Introduction • Two competing I/O systems in C++. • Standard I/O Library,stdio • Stream I/O Library, iostream • Never use both Library in the same program. Ch 10. Input/Output

  3. The stdio Library • Inherited from the C. • 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. Ch 10. Input/Output

  4. Examples of stdio # include <cstdio> 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 Ch 10. Input/Output

  5. Formatted Output • The printf facility works only for formatted primitive values, such as integers and floats. • Not easily extendable to user-defined data types. • Always verify that formatting commands match the argument types. Ch 10. Input/Output

  6. 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 Ch 10. Input/Output

  7. 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 Ch 10. Input/Output

  8. The Stream I/O Facility • Whenever possible use the Stream I/O Library rather than the Standard I/O Library. • Use the ability to overload function names in C++. • Better possibilities for extendability as well as improved error detection. Ch 10. Input/Output

  9. Figure 10.2 Various Overloading Versions of the << Operator 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 usvalue = value; // print non-negative number out << usvalue; return out; } Ch 10. Input/Output

  10. inline char digitCharacter(unsigned int value) { // convert non-negative integer digit into printable digit // assume value is less than nine 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); // print single char } return out; } Ch 10. Input/Output

  11. Examples of Stream I/O # include <iostream> cout << "n " << n << " m " << m << " average " << (n+m)/2.0 << '\n'; • Easy to provide formatting capabilities for a new data type. 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; Ch 10. Input/Output

  12. Another Examples • A manipulator is used to change features of the I/O system. ostream & endl (ostream & out) {// write the end of line characterout << '\n';// then flush the bufferout.fflush();// then return the bufferreturn out; } ostream & operator << (ostream & out, ostream & (*fun)(ostream &)) {// simply execute functionreturn fun (out); } Ch 10. Input/Output

  13. Stream Input • Stream input always 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 Ch 10. Input/Output

  14. String Streams • A string stream writes to or reads from a string. • Must include the sstream header file. • ostringstream creates an output stream. • Values are buffered in an internal string and can be accessed with the member function str. • Useful for formatting complex output; not only perform catenation, but also automatically convert the right argument from numerous primitive data types into character values. • Can be used as the string catenation operator + commonly used in Java Ch 10. Input/Output

  15. # include <sstream> int n = ...; int m = ...; ostringstream formatter; formatter << "the average of " << n << " and " << m << " is " << ((n + m)/2.0); string s = formatter.str(); string text = "Isn't this a wonderful feature"; istringstream breaker(text); string word; while (breaker >> word)cout << word << endl; // print each word on a separate line Ch 10. Input/Output

  16. 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 creat streams that are attached to input and output files. Ch 10. Input/Output

  17. 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. Ch 10. Input/Output

  18. An Example Program # include <iostream> # include <string> int main() {int wordCount = 0;double totalWordLen = 0;double totalSenCount = 0;string word;while (cin >> word) { int wordLen = word.length(); wordCount++; if (word[wordLen-1] == '.') { totalWordLen += (wordLen-1); totalSenCount++; } else { totalWordLen += wordLen; }} Ch 10. Input/Output

  19. cout << "total number of words " << wordCount << endl;if (wordCount > 0)cout << "average word length " << totalWordLen / wordCount << endl;cout << "total number of sentences " << totalSenCount << endl; if (totalSenCount > 0) cout << "average sentence length " << wordCount / totalSenCount << endl;return 0; } Ch 10. Input/Output

More Related