Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Ch 10. Input/Output1 Ch. 10 Input/Output Oregon State University Timothy Budd."— Presentation transcript:

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

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

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

4 Ch 10. Input/Output4 Examples of stdio # include 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 string char 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 fp int c = fgetc(fp); // read character from fp char * msg = "unrecoverable program error"; fputs(msg, stderr); // write message to standard error output

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

6 Ch 10. Input/Output6 Examples of Formatted Output %dinteger decimal value %ointeger printed as octal %xinteger printed as hexadecimal %cinteger printed as character %uunsigned integer decimal value %ffloating point value %gfloating point value %snull terminated string value %percent sign

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

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

9 Ch 10. Input/Output9 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; }

10 Ch 10. Input/Output10 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; }

11 Ch 10. Input/Output11 Examples of Stream I/O # include 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;

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

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

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

15 Ch 10. Input/Output15 # include 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

16 Ch 10. Input/Output16 File Streams A file stream is a stream that reads from or writes to a file. Must include the header file # include 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.

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

18 Ch 10. Input/Output18 An Example Program # include 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; } }

19 Ch 10. Input/Output19 cout 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; }


Download ppt "Ch 10. Input/Output1 Ch. 10 Input/Output Oregon State University Timothy Budd."

Similar presentations


Ads by Google