Ch. 10 Input/Output - PowerPoint PPT Presentation

About This Presentation
Title:

Ch. 10 Input/Output

Description:

Ch' 10 InputOutput – PowerPoint PPT presentation

Number of Views:39
Avg rating:3.0/5.0
Slides: 20
Provided by: seungs
Category:
Tags: double | input | output

less

Transcript and Presenter's Notes

Title: Ch. 10 Input/Output


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

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.

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.

4
Examples of stdio
  • include ltcstdiogt
  • 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 buffer120gets(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

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.

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

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 buffer180
  • 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
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
Figure 10.2 Various Overloading Versions of the
ltlt Operator
  • ostream operator ltlt (ostream out, const int
    value)
  • // print signed integer values on a
    stream unsigned int usvalue if (value lt 0)
    // print leading minus sign out ltlt
    '-' usvalue - value else usvalue
    value // print non-negative number out ltlt
    usvalue return out

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 ltlt (ostream out, const
    unsigned int value)
  • // print unsigned integer values on a stream
  • if (value lt 10) out ltlt digitCharacter(value)
    else out ltlt (value / 10) // recursive
    call out ltlt digitCharacter(value 10)
  • // print single char return out

11
Examples of Stream I/O
  • include ltiostreamgt
  • cout ltlt "n " ltlt n ltlt " m " ltlt m ltlt " average " ltlt
    (nm)/2.0 ltlt '\n'
  • Easy to provide formatting capabilities for a new
    data type.
  • ostream operator ltlt (ostream out, const
    rational value) // print representation of
    rational number on an output stream out ltlt
    value.numerator() ltlt '/' ltlt value.denominator()
    return out
  • rational frac(3,4)
  • cout ltlt "fraction of " ltlt 3 ltlt " and " ltlt 4 ltlt "
    is
  • ltlt frac ltlt endl

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 ltlt '\n'// then flush the
    bufferout.fflush()// then return the
    bufferreturn out
  • ostream operator ltlt (ostream out, ostream
    (fun)(ostream )) // simply execute
    functionreturn fun (out)

13
Stream Input
  • Stream input always ignores white space.
  • cin gtgt intval
  • while (cin gtgt intval) // process
    intval ...// reach this point on end of
    input...
  • Visualize gtgt and ltlt as arrows
  • Input operator, gtgt x points data into x
  • Output operator, ltlt x copies data out of x

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

15
  • include ltsstreamgt
  • int n ...
  • int m ...
  • ostringstream formatter
  • formatter ltlt "the average of " ltlt n ltlt " and "
  • ltlt m ltlt " is " ltlt ((n m)/2.0)
  • string s formatter.str()
  • string text "Isn't this a wonderful feature"
  • istringstream breaker(text)
  • string word
  • while (breaker gtgt word)cout ltlt word ltlt endl //
    print each word on a separate line

16
File Streams
  • A file stream is a stream that reads from or
    writes to a file.
  • Must include the header file
  • include ltfstreamgt
  • 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
  • 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 ltlt " cannot open file " ltlt
    fileName
  • else ofd ltlt "first line in file" ...
  • File operations in C throw far fewer exceptions
    than do in Java.

18
An Example Program
  • include ltiostreamgt
  • include ltstringgt
  • int main() int wordCount 0double
    totalWordLen 0double totalSenCount
    0string wordwhile (cin gtgt word) int
    wordLen word.length() wordCount if
    (wordwordLen-1 '.') totalWordLen
    (wordLen-1) totalSenCount else
    totalWordLen wordLen

19
  • cout ltlt "total number of words " ltlt wordCount ltlt
    endlif (wordCount gt 0)cout ltlt "average word
    length "
  • ltlt totalWordLen / wordCount ltlt endlcout ltlt
    "total number of sentences "
  • ltlt totalSenCount ltlt endl
  • if (totalSenCount gt 0) cout ltlt "average
    sentence length "
  • ltlt wordCount / totalSenCount ltlt
    endlreturn 0
Write a Comment
User Comments (0)
About PowerShow.com