CHAPTER 3 INPUT/OUTPUT - PowerPoint PPT Presentation

1 / 31
About This Presentation
Title:

CHAPTER 3 INPUT/OUTPUT

Description:

CHAPTER 3 INPUT/OUTPUT In this chapter, you will: Learn what a stream is and examine input and output streams Explore how to read data from the standard input device ... – PowerPoint PPT presentation

Number of Views:258
Avg rating:3.0/5.0
Slides: 32
Provided by: abc3171
Category:

less

Transcript and Presenter's Notes

Title: CHAPTER 3 INPUT/OUTPUT


1
CHAPTER 3 INPUT/OUTPUT
2
  • In this chapter, you will
  • Learn what a stream is and examine input and
    output streams
  • Explore how to read data from the standard input
    device
  • Learn how to use predefined functions in a
    program
  • Explore how to use the input stream functions
    get, ignore, fill, putback, and peek
  • Become familiar with input failure
  • Learn how to write data to the standard output
    device
  • Discover how to use manipulators in a program to
    format output
  • Learn how to perform input and output operations
    with the string data type
  • Become familiar with file input and output

3
  • I/O STREAMS AND STANDARD I/O DEVICES
  • To use cin and cout every C program must use
    the preprocessor directive
  • include ltiostreamgt
  • cingtgtpayRate Extraction Operator (gtgt)
  • cingtgtpayRategtgthoursWorked
  • When scanning for the next input, gtgt skips all
    leading whitespaces until the data has read.
  • Whitespace characters consist of blanks and
    certain nonprintable characters, such as tabs and
    the newline character.

4
  • Example 3-1
  • int a,b
  • double z
  • char ch,ch1,ch2
  • Statement Input Value Stored in Memory
  • 2 cingtgtch AB ch'A', 'B' is held for
    later input
  • 4 cingtgta 46.35 a46, .35 is held for
    later input
  • 6 cingtgtz 39 z39.0
  • 9 cingtgtagtgtchgtgtz 57 A 26.9 a57, ch'A', z26.9
  • 12 cingtgtagtgtchgtgtz 57A26.9 a57, ch'A', z26.9
  • 15 cingtgtagtgtbgtgtz 11 34 a11, b34, Computer
    waits for the next number

5
  • USING PREDEFINED FUNCTIONS IN A PROGRAM
  • A function, also called subprogram, is a set of
    instructions.
  • When a function is activated, that is, executed,
    it accomplishes something.
  • The function main is executed automatically when
    we execute a program.
  • Other functions are executed only when they are
    called.
  • The programming language C comes with a wealth
    of functions.
  • Predefined functions are organized as a
    collection of libraries, called header files.
  • pow(2,3) 23 8 and pow(4,0.5) 40.5 2.
  • In pow(2,3), the parameters are 2 and 3.
  • An expression such as pow(2,3) is called a
    function call.
  • The header file cmath contains the specification
    of the function pow.

6
  • cin and the get Function
  • Consider the declaration
  • char ch1, ch2
  • int num
  • The get function inputs the very next character
    (including whitespaces) from the input stream and
    stores in the memory location indicated by its
    argument.
  • The syntax of cin together with the get function
    to read a character is
  • A 25
  • We can effectively use the get function as
    follows
  • cin.get(ch1)
  • cin.get(ch2)
  • cingtgtnum
  • to store A in ch1, blank in ch2, and 25 in num.

7
  • cin and the ignore Function
  • To process partial data, say with in a line, we
    can effectively use the ignore function to
    discard some portion of the input.
  • Consider the following statement
  • cin.ignore(100,'\n')
  • The execution of this statement will ignore the
    next 100 characters or until the newline
    character is found whichever comes first.
  • The execution of the statement
  • cin.ignore(100,'A')
  • will result in ignoring the first 100 characters
    or until the character 'A' is found, whichever
    comes first.

8
  • Example 3-2
  • int a,b
  • Suppose the input is
  • 25 67 89 43 72
  • 12 78 34
  • Consider the statements
  • cingtgta
  • cin.ignore(100,'\n')
  • cingtgtb
  • The first statement cingtgta stores 25 in a.
  • The second statement, cin.ignore(100,'\n')
    discards all of the remaining numbers in the
    first line.
  • The third statement cingtgtb stores 12 (from the
    next line) in b.

9
  • Example 3-3
  • char ch1,ch2
  • Suppose the input is
  • Hello there. My name is Mickey.
  • Now consider the statements
  • cingtgtch1
  • cin.ignore(100,'.')
  • cingtgtch2
  • The first statement cingtgtch1 stores 'H' in ch1.
  • The second statement, cin.ignore(100,'.' )
    results in ignoring all characters until '.'
    (period).
  • The third statement cingtgtch2 stores 'M' (from
    the same line) in ch2.

10
  • The peek and the putback Functions
  • The putback function places the previous
    character extracted by the get function from an
    input stream back to that stream.
  • The peek function returns the next character from
    the input stream but it does not remove the
    character from that stream, that is, the next
    input character would be the same.
  • The syntax to use the function peek is
  • char ch
  • ch cin.peek()
  • cin.get(ch)
  • cin.putback(ch)

11
  • INPUT FAILURE
  • If the input data did not match the corresponding
    variables, the program would run into problems.
  • Trying to read a letter into an int or double
    variable would result in an input failure.
  • Consider the following statements
  • int a, b, c
  • double x
  • If the input is W 54
  • then the statement
  • cingtgtagtgtb
  • would result in an input failure because you are
    trying to input the character 'W' into the int
    variable a.

12
  • Once an input stream enters a fail state, all
    further I/O statements using that stream are
    ignored.
  • Unfortunately, the program quietly continues to
    execute with whatever values are stored in
    variables and produce incorrect results.
  • The clear Function
  • When an input stream enters the fail state, the
    system ignores all further I/O using that stream.
    You can use the stream function clear to restore
    the input stream to a working state.
  • The syntax to use the function clear is
  • cin.clear()

13
  • OUTPUT AND FORMATTING OUTPUT
  • Syntax of cout when used together with the
    insertion operator ltlt is
  • coutltltexpression or manipulator
  • ltltexpression or manipulator...
  • expression is evaluated, its value is printed,
    and manipulator is used to format the output.
  • The simplest manipulator that you have used so
    far is endl, which is used to move the cursor to
    the beginning of the next line.
  • To use the manipulator, the program must include
    the header file iomanip.
  • include ltiomanipgt

14
  • setprecision
  • The general form of setprecision is
  • setprecision(n)
  • where n is the number of decimal places.
  • coutltltsetprecision(2)
  • cout ltlt setprecision(2) ltlt num
  • will output all decimal numbers up to two decimal
    places until it is reset.
  • The following statement sets the output of
    floating-point numbers in a fixed decimal format
    on the standard output device
  • coutltltfixed

15
  • showpoint
  • If the decimal part of a decimal number is zero,
    then when you instruct the computer to output the
    decimal number in a fixed decimal format, the
    output may not show the decimal point and the
    decimal part.To force the output to show the
    decimal point and trailing zeros, you use the
    manipulator showpoint.
  • The following statement sets the output of a
    floating-point number in a fixed decimal format
    with the decimal point and trailing zeros on the
    standard output device
  • coutltltfixedltltshowpoint

16
  • C provides the manipulator setiosflags, to set
    the flags iosfixed, iosscientific, and
    iosshowpoint.
  • To use the manipulator setiosflags , the program
    must include the header file iomanip.
  • coutltltsetiosflags(iosfixed)
  • coutltltsetiosflags(iosshowpoint)
  • You can specify more than one flag in the
    manipulator setiosflags by separating the flags
    with the symbol .
  • The following statement sets both the flags
    iosfixed and iosshowpoint on the standard
    output device
  • coutltltsetiosflags(iosfixed iosshowpoint)
  • C provides the manipulator resetiosflags to
    reset the flags that was setted.
  • cout ltlt resetiosflags(iosfixed)

17
  • setw
  • setw(n) - output the value of the next expression
    in n columns.
  • The output is right justified.
  • If the number of specified columns is less than
    the number of columns required by the output,
    then the output is automatically expanded to the
    required number of columns.
  • Unlike setprecision, which controls the output of
    all floating-point numbers until it is reset,
    setw controls the output of only the next
    expression.
  • To use the manipulator setw, the program must
    include the header file iomanip.
  • int num 25
  • cout ltlt setw(4) ltlt num
    --25

18
  • ADDITIONAL OUTPUT FORMATTING TOOLS
  • fill and setfill
  • In the manipulator setw if the number of columns
    specified are more than the number of columns
    required by the expression, the output of the
    expression is right justified and the unused
    columns to the left are filled with spaces.
  • The output stream variables, such as cout, can
    use the function fill and/or the manipulator
    setfill to fill the unused columns with a
    character other than the space.
  • The syntax to use the function fill is
  • coutltltsetfill('')
  • sets the filling character to ''.
  • int num 25
  • cout ltlt setw(4) ltlt setfill()ltlt num
    25

19
  • The left and right Manipulators
  • To left-justify the output, you use the
    manipulator left.
  • The following statement sets the output to be
    left-justified on the standard output device
  • int num 25
  • cout ltlt left
  • cout ltlt setw(4) ltlt num
    25--
  • cout ltlt setw(4) ltlt setfill()ltlt num
    25
  • The following statement sets the output to be
    right-justified on the standard output device
  • cout ltlt right
  • cout ltlt setw(4) ltlt num
    25

20
  • The flush Function
  • Both the manipulator endl and the newline escape
    sequence \n position the cursor at the beginning
    of the next line on the output device.
  • When a program sends output to an output device,
    the output first goes to the buffer in the
    computer.
  • Whenever the buffer becomes full, the output is
    sent to the output device.
  • As soon as the manipulator endl is encountered,
    the output from the buffer is sent to the output
    device immediately, even if the buffer is not
    full.
  • The manipulator endl positions the cursor at the
    beginning of the next line on an output device
    and helps clear the buffer.
  • It is quite possible that sometimes you may not
    see the entire output because when the program
    terminates, the buffer at that time may not be
    full.

21
  • In C, you can use the function flush to clear
    the buffer, even if the buffer is not full.
  • In contrast to the manipulator endl, the function
    flush does not move the cursor to the beginning
    of the next line.
  • Just like endl, the function flush can be used as
    a manipulator. In such a case, flush is used in
    an output statement without the parentheses. For
    example, the following statement sends the output
    from the buffer to the standard output device
  • coutltlt"Enter an integer "ltltflush

22
  • You can disable the manipulator by using the
    stream member function .
  • Member function comes with the Dot operator
  • cout.unsetf(iosfixed)
  • cout.unsetf(iosleft)
  • cout.precision(2)
  • cout.setf(iosfixed iosshowpoint)
  • cout.width(4)
  • cout.fill('')
  • cout.flush()

23
  • Input/Output and the string Type
  • You can use an input stream variable, such as
    cin, and the extraction operator gtgt to read a
    string into a variable of the data type string.
  • If the input is the string "Shelly", the
    following code stores this input into the string
    variable name
  • string name // declaration
  • cingtgtname // input statement
  • The extraction operator skips any leading
    whitespace characters and that reading stops at a
    whitespace character.
  • You cannot use the extraction operator to read
    strings that contain blanks.
  • Alice Wonderland name

Alice
24
  • To read a string containing blanks, you can use
    the function getline .
  • The syntax to use the function getline is
  • getline(istreamVar, strVar)
  • where istreamVar is an input stream variable and
    strVar is a variable of the type string. The
    reading is delimited by the newline character,
    '\n'.
  • string name
  • getline(cin,name)
  • Alice Wonderland name
  • The function getline reads until it reaches the
    end of the current line.
  • The newline character is also read but not stored
    in the string variable.

Alice Wonderland
25
  • Consider the following statement
  • string myString
  • If the input is 29 characters,
  • bbbbHello there. How are you?
  • where b represents a blank, after the statement
  • getline(cin,myString)
  • the value of myString is
  • myString " Hello there. How are you?"

26
  • File Input/Output
  • File An area in secondary storage used to hold
    information.
  • For file I/O, the following steps are necessary.
  • 1. Include the header file fstream in the
    program. So the following statement is needed.
  • include ltfstreamgt
  • 2. Declare file (fstream) variables. For example
    the statements
  • ifstream inData
  • ofstream outData
  • declare the variable inData for input and
    outData for output. That is, inData is an input
    (file) stream variable and outData is an output
    (file) stream variable.

27
  • 3. Open Files
  • The general syntax for opening a file is
  • fileStreamVariable.open(sourceName,
  • fileOpeningMode)
  • Here fileStreamVariable is a file stream
    variable, sourceName is the name of the
    input/output file, and fileOpeningMode specifies
    the mode in which the file is to be opened.
  • inData.open("Aprog.dat") //open input file
  • outData.open("Aprog.out") //open output file

28
(No Transcript)
29
  • I/O with input and output files
  • Use the (file) stream variable together with gtgt
    or ltlt or with other functions for input/Output.
  • The syntax for using gtgt or ltlt with file variables
    is exactly similar to the syntax of cin and cout.
  • The statement
  • inDatagtgtpayRate
  • reads the data from the file prog.dat and stores
    it in the variable payRate
  • The statement
  • outDataltlt"The pay check is "ltltpayltltendl
  • stores the output line, which is The pay check
    is 565.78, in the file prog.out. Here we are
    assuming that the pay was calculated as 565.78.

30
  • Close File
  • inData.close()
  • outData.close()

31
  • include ltfstreamgt
  • //Add additional header files you use
  • using namespace std
  • int main()
  • //Declare file stream variables such as the
    following
  • ifstream inData
  • ofstream outData
  • ...
  • //Open files
  • inData.open("Aprog.dat") //open input file
  • outData.open("Aprog.out") // open output file
  • //Code for data manipulation
  • //Close files
  • inData.close()
  • outData.close()
  • return 0
Write a Comment
User Comments (0)
About PowerShow.com