CHAPTER 3 INPUT/OUTPUT - PowerPoint PPT Presentation

1 / 106
About This Presentation
Title:

CHAPTER 3 INPUT/OUTPUT

Description:

The following statement sets the output to be right-justified on the standard output device: cout – PowerPoint PPT presentation

Number of Views:447
Avg rating:3.0/5.0
Slides: 107
Provided by: abc7266
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
  • Input/Output Streams
  • I/O is a sequence of bytes, called a stream of
    bytes, from the source to the destination.
  • The bytes are usually characters, unless the
    program requires other types of information such
    as a graphic image or digital speech.
  • A stream is a sequence of characters from the
    source to the destination.
  • Input Stream A sequence of characters from an
    input device to the computer.
  • Output Stream A sequence of characters from
    the computer to an output device.

4
  • I/O STREAMS AND STANDARD I/O DEVICES
  • To extract (that is, receive) data from keyboard
    and send output to the screen, every C program
    must use the header file iostream.
  • This header file, iostream, contains definitions
    of two data types, istream (input stream) and
    ostream (output stream).
  • The header file, iostream, contains the
    declaration of two variables, cin (stands for
    common input), pronounced see-in, and cout
    (stands for common output), pronounced see-out,
    and the declaration is similar to the following
    C statements
  • istream cin
  • ostream cout
  • To use cin and cout every C program must use
    the preprocessor directive
  • include ltiostreamgt

5
  • Variables of the type istream are called input
    stream variables.
  • Variables of the type ostream are called output
    stream variables.
  • A stream variable is either an input stream
    variable or an output stream variable.

6
  • cin and the Extraction Operator (gtgt)
  • Consider the following C statement
  • cingtgtpayRate
  • If you type 15.50, the value stored in payRate
    after the execution of this statement is 15.50.
  • The extraction operator gtgt is binary. The
    left-hand operand is an input stream variable
    such as cin. The right-hand operand is a variable
    of a simple data type.
  • The purpose of an input statement is to read and
    store values in a memory location and only
    variables refer to memory locations, the items
    (that is, right hand operand in the case of the
    extraction operator, gtgt) must be a variable in an
    input statement.

7
  • The syntax of an input statement using cin and
    the extraction operator gtgt is
  • cingtgtvariablegtgtvariable...

8
  • Every occurrence of gtgt extracts the next data
    item from the input stream.
  • You can read both payRate and hoursWorked via a
    single cin statement by using the following code
  • cingtgtpayRategtgthoursWorked
  • There is no difference between the preceding cin
    statement and the following two cin statements.
  • cingtgtpayRate
  • cingtgthoursWorked
  • When scanning for the next input, gtgt skips all
    whitespaces.
  • Whitespace characters consist of blanks and
    certain nonprintable characters, such as tabs and
    the newline character.

9
  • Whether the input is
  • 15.50 48.30
  • or
  • 15.50 48.30
  • or
  • 15.50
  • 48.30
  • The input statement
  • cingtgtpayRategtgthoursWorked
  • would store 15.50 in payRate and 48.30 in
    hoursWorked.

10
  • Suppose the input is 2. How does gtgt distinguish
    between character 2 and the number 2?
  • This is distinguished by the right hand operand
    of gtgt.
  • If the right hand operand, that is, variable, is
    of type char, input 2 is treated as character 2
    (recall that in this case, the ASCII value of 2
    will be stored). And if the right-hand operand is
    of the type int (or double), input 2 is treated
    as the number 2.
  • Now consider the input 25 and the statement
  • cingtgta
  • where a is a variable of some simple data
    type.
  • If a is of the data type char, then only the
    single character 2 will be stored in a.
  • If a is of the data type, say int, then 25 will
    be stored in a.
  • If a is of the type double, then the input 25 is
    converted to a decimal number with zero decimal
    part.

11
  • Consider the statement
  • cingtgta
  • where a is a variable of some simple data type.

12
  • When reading data into a char variable, after
    skipping any leading whitespace characters, the
    extraction operator gtgt finds and stores only the
    next character reading stops after a single
    character.
  • To read data into an int or double variable,
    after skipping all leading whitespace characters
    and reading the plus or minus sign (if any), the
    extraction operator gtgt reads the digits of the
    number, including the decimal point for
    floating-point variables, and stops when it finds
    a whitespace character or a character other than
    a digit.

13
  • Example 3-1
  • int a,b
  • double z
  • char ch,ch1,ch2
  • Statement Input Value Stored in Memory
  • 1 cingtgtch A ch'A'
  • 2 cingtgtch AB ch'A', 'B' is held for
    later input
  • 3 cingtgta 48 a48
  • 4 cingtgta 46.35 a46, .35 is held for
    later input
  • 5 cingtgtz 74.35 z74.35
  • 6 cingtgtz 39 z39.0
  • 7 cingtgtzgtgta 65.78 38 z65.78, a38
  • 8 cingtgtagtgtb 4 60 a4, b60
  • 9 cingtgtagtgtchgtgtz 57 A 26.9 a57, ch'A', z26.9

14
  • 10 cingtgtagtgtchgtgtz 57 A
  • 26.9 a57, ch'A', z26.9
  • 11 cingtgtagtgtchgtgtz 57
  • A
  • 26.9 a57, ch'A', z26.9
  • 12 cingtgtagtgtchgtgtz 57A26.9 a57, ch'A', z26.9
  • 13 cingtgtzgtgtchgtgta 36.78B34 z36.78, ch'B',
    a34
  • 14 cingtgtzgtgtchgtgta 36.78
  • B34 z36.78, ch'B', a34
  • 15 cingtgtagtgtbgtgtz 11 34 a11, b34, Computer
    waits for the next number

15
  • 16 cingtgtagtgtz 46 32.4 68 a46, z32.4, 68 is
    held for later input
  • 17 cingtgtchgtgta 256 ch'2', a56
  • 18 cingtgtagtgtch 256 a256, computer waits
    for the input value for ch.
  • 19 cingtgtch1gtgtch2 A B ch1 'A', ch2 'B
  • During program execution, when entering character
    data such as letters, you do not enter the single
    quotes around the character.
  • Entering a char value into an int or double
    variable causes serious errors, called input
    failure.

16
  • 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.

17
  • Predefined functions are organized as a
    collection of libraries, called header files.
  • A particular header file may contain several
    functions.
  • To use a particular function, you need to know
    the name of the function and a few other things.
  • A very useful function, pow, called the power
    function, can be used to calculate xy in a
    program. That is, pow(x,y) xy.
  • pow(2,3) 23 8 and pow(4,0.5) 40.5 2.
  • The numbers x and y that you use in the function
    pow are called the arguments or parameters of the
    function pow.
  • 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.

18
  • To use a predefined function in a program, you
    need to know the name of the header file
    containing the specification of the function and
    include that header file in the program.
  • In addition, you need to know the name of the
    function, the number of parameters the function
    takes, and the type of each parameter. You must
    also be aware of what the function is going to
    do.
  • To use the function pow, you must include the
    header file cmath.
  • The function pow has two parameters, both of
    which are numbers. The function calculates the
    first parameter to the power of the second
    parameter.

19
  • cin and the get Function
  • Consider the declaration
  • char ch1, ch2
  • int num
  • and the input
  • A 25
  • Now consider the statement
  • cingtgtch1gtgtch2gtgtnum
  • When the computer executes this statement, A is
    stored in ch1, blank is skipped by gtgt, 2 is
    stored in ch2, and 5 is stored in num.
  • If we intended to store A in ch1, blank in ch2
    and 25 in num? It is clear that we can not use
    the extraction operator gtgt.

20
  • 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
  • cin.get(varChar)
  • where varChar is a char variable.
  • varChar is called the argument or parameter of
    the function.
  • The next input character is stored in varChar.

21
  • Now, again, consider the input
  • 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.
  • The above set of statements is equivalent to the
    following
  • cingtgtch1
  • cin.get(ch2)
  • cingtgtnum

22
  • 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.
  • The syntax to use the function ignore is
  • cin.ignore(intExp,chExp)
  • where intExp is an integer expression yielding
    an integer value and chExp is a char expression.
  • Suppose intExp yields a value, say m. This
    statement says, ignore the next m characters or
    until the character specified by chExp, whichever
    comes first.

23
  • 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.

24
  • 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.

25
  • 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.

26
  • 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 putback is
  • istreamVar.putback(ch)
  • where istreamVar is an input stream variable,
    such as cin, and ch is a char variable.
  • The syntax to use the function peek is
  • ch istreamVar.peek()
  • where istreamVar is an input stream variable,
    such as cin, and ch is a char variable.

27
  • Example 3-4
  • //Functions peek and putback
  • include ltiostreamgt
  • using namespace std
  • int main()
  • char ch
  • coutltlt"Line 1 Enter a string " //Line 1
  • cin.get(ch) //Line 2
  • coutltltendl //Line 3
  • coutltlt"Line 4 After first cin.get(ch) "
  • ltlt"ch "ltltchltltendl //Line 4

28
  • cin.get(ch) //Line 5
  • coutltlt"Line 6 After second cin.get(ch) "
  • ltlt"ch "ltltchltltendl //Line 6
  • cin.putback(ch) //Line 7
  • cin.get(ch) //Line 8
  • coutltlt"Line 9 After putback and then "
  • ltlt"cin.get(ch) ch "ltltchltltendl //Line 9
  • ch cin.peek() //Line 10
  • coutltlt"Line 11 After cin.peek() ch "
  • ltltchltltendl //Line 11

29
  • cin.get(ch) //Line 12
  • coutltlt"Line 13 After cin.get(ch) ch "
  • ltltchltltendl //Line 13
  • return 0
  • Sample Run In this sample run, the user input is
    in red.
  • Line 1 Enter a string abcd
  • Line 4 After first cin.get(ch) ch a
  • Line 6 After second cin.get(ch) ch b
  • Line 9 After putback and then cin.get(ch) ch
    b
  • Line 11 After cin.peek() ch c
  • Line 13 After cin.get(ch) ch c

30
  • The Dot Notation Between I/O Stream Variables and
    I/O Functions A Precaution
  • To use the get function we used statements such
    as
  • cin.get(ch)
  • Missing dot will result in compile time error.
    For example, in the statement
  • cin.get(ch)
  • cin and get are two separate identifiers, while
    in the statement
  • cinget(ch)
  • cinget becomes a new identifier and the compiler
    might be trying to resolve the problem of an
    undeclared identifier in the program. Similarly,
    missing parentheses will result in compile time
    error.

31
  • Several functions are associated with an istream
    variable, each doing a specific job.
  • The functions get, ignore, and so on are members
    of the data type istream.
  • Called the dot notation, the dot separates the
    input stream variable name from the member, or
    function, name.
  • In C, the dot is an operator called the member
    access operator.
  • C has a special name for the data types istream
    and ostream.
  • The data types istream and ostream are called
    classes.
  • The variables cin and cout also have special
    names, called objects. cin is called an istream
    object
  • cout is called an ostream object.
  • Stream variables are called stream objects.

32
  • INPUT FAILURE
  • Many things can go wrong during program
    execution.
  • A program that is syntactically correct might
    produce incorrect results.
  • Suppose that a part-time employees paycheck is
    calculated by using the following formula
  • wages payRate hoursWorked
  • If you accidentally type in place of , the
    calculated wages would be incorrect, even though
    the statement containing a is syntactically
    correct.

33
  • What about an attempt to read invalid data?
  • What would happen if you tried to input a letter
    into an int variable?
  • 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.

34
  • 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.

35
  • If the input is
  • 35 67.93 48 78
  • then the input statement
  • cingtgtagtgtxgtgtb
  • would result in storing 35 in a, 67.93 in x, and
    48 in b.
  • Now consider the following read statement with
    the previous input (the input with three values)
  • cingtgtagtgtbgtgtc
  • This statement stores 35 in a and 67 in b. The
    reading stops at . (the decimal point). Because
    the next variable c is of the data type int, the
    computer tries to read . into c, which is an
    error. The input stream then enters a state
    called the fail state.

36
  • What actually happens when the input stream
    enters the fail state?
  • 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.

37
  • Example 3-5
  • //Input Failure program
  • include ltiostreamgt
  • using namespace std
  • int main()
  • int a 10 //Line 1
  • int b 20 //Line 2
  • int c 30 //Line 3
  • int d 40 //Line 4
  • coutltlt"Line 5 Enter four integers "
    //Line 5
  • cingtgtagtgtbgtgtcgtgtd //Line 6
  • coutltltendl //Line 7

38
  • coutltlt"Line 8 The numbers you entered are"
  • ltltendl //Line 8
  • coutltlt"Line 9 a "ltltaltlt", b "ltltb
  • ltlt", c "ltltcltlt", d "ltltdltltendl //Line 9
  • return 0
  • Sample Run 1 The user input is in red.
  • Line 5 Enter four integers 34 K 67 28
  • Line 8 The numbers you entered are
  • Line 9 a 34, b 20, c 30, d 40

39
  • 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
  • istreamVar.clear()
  • Here istreamVar is an input stream variable, such
    as cin.

40
  • 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.

41
  • setprecision
  • The general form of setprecision is
  • setprecision(n)
  • where n is the number of decimal places.
  • The statement
  • coutltltsetprecision(2)
  • will output all decimal numbers up to two decimal
    places until it is reset.
  • To use the manipulator setprecision, the program
    must include the header file iomanip.
  • include ltiomanipgt

42
  • fixed
  • To output floating-point numbers in a fixed
    decimal format, you use the manipulator fixed.
  • The following statement sets the output of
    floating-point numbers in a fixed decimal format
    on the standard output device
  • coutltltfixed
  • After the preceding statement executes, all
    floating-point numbers are displayed in the
    fixed-decimal format until the manipulator fixed
    is disabled.

43
  • You can disable the manipulator fixed by using
    the stream member function unsetf.
  • The following statement disables the manipulator
    fixed on the standard output device, you use
  • cout.unsetf(iosfixed)
  • After the manipulator fixed is disabled, the
    output of the floating-point numbers return to
    their default settings.
  • The manipulator scientific is used to output
    floating-point numbers in scientific format.

44
  • 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
    decimal numbers with a decimal point and trailing
    zeros on the standard input device
  • coutltltshowpoint
  • 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

45
  • Example 3-7
  • //Example setprecision, fixed, showpoint
  • include ltiostreamgt
  • include ltiomanipgt
  • using namespace std
  • int main()
  • double x,y,z
  • x 15.674 //Line 1
  • y 235.73 //Line 2
  • z 9525.9864 //Line 3
  • coutltltfixedltltshowpoint //Line 4

46
  • coutltltsetprecision(2)
  • ltlt"Line 5 setprecision(2)"ltltendl //Line 5
  • coutltlt"Line 6 x "ltltxltltendl //Line 6
  • coutltlt"Line 7 y "ltltyltltendl //Line 7
  • coutltlt"Line 8 z "ltltzltltendl //Line 8
  • coutltltsetprecision(3)
  • ltlt"Line 9 setprecision(3)"ltltendl //Line 9
  • coutltlt"Line 10 x "ltltxltltendl //Line 10
  • coutltlt"Line 11 y "ltltyltltendl //Line 11
  • coutltlt"Line 12 z "ltltzltltendl //Line 12

47
  • coutltltsetprecision(4)
  • ltlt"Line 13 setprecision(4)"ltltendl //Line 13
  • coutltlt"Line 14 x "ltltxltltendl //Line 14
  • coutltlt"Line 15 y "ltltyltltendl //Line 15
  • coutltlt"Line 16 z "ltltzltltendl //Line 16
  • coutltlt"Line 17 "
  • ltltsetprecision(3)ltltxltlt" "
  • ltltsetprecision(2)ltltyltlt" "
  • ltltsetprecision(4)ltltzltltendl //Line 17
  • return 0

48
  • Output
  • Line 5 setprecision(2)
  • Line 6 x 15.67
  • Line 7 y 235.73
  • Line 8 z 9525.99
  • Line 9 setprecision(3)
  • Line 10 x 15.674
  • Line 11 y 235.730
  • Line 12 z 9525.986
  • Line 13 setprecision(4)
  • Line 14 x 15.6740
  • Line 15 y 235.7300
  • Line 16 z 9525.9864
  • Line 17 15.674 235.73 9525.9864

49
  • The stream function setf can be used to set
    fixed, scientific, and showpoint.
  • In this case, fixed, scientific, and showpoint
    are referred to as iosfixed, iosscientific,
    and iosshowpoint, respectively, and are called
    formatting flags.
  • Both the flags iosfixed and iosscientific are
    part of iosfloatfield, which is a data type in
    C.
  • When setting the fixed or scientific flag, to
    ensure that only either the iosfixed or
    iosscientific flag is set, you must pass
    iosfloatfield as a second argument to the
    function setf.
  • cout.setf(iosfixed,iosfloatfield)

50
  • The following statement sets the flag
    iosshowpoint to output floating-point numbers
    with a decimal point and trailing zeros on the
    standard output device
  • cout.setf(iosshowpoint)

51
  • 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.
  • The following statement uses the manipulator
    setiosflags to set the flags iosfixed and
    iosshowpoint on the standard output device
  • coutltltsetiosflags(iosfixed)
  • coutltltsetiosflags(iosshowpoint)

52
  • 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)

53
  • 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.

54
  • Example 3-8
  • //Example setw
  • include ltiostreamgt
  • include ltiomanipgt
  • using namespace std
  • int main()
  • int x 19 //Line 1
  • int a 345 //Line 2
  • double y 76.384 //Line 3
  • coutltltfixedltltshowpoint //Line 4

55
  • coutltlt"12345678901234567890"ltltendl //Line 5
  • coutltltsetw(5)ltltxltltendl //Line 6
  • coutltltsetw(5)ltltaltltsetw(5)ltlt"Hi"
  • ltltsetw(5)ltltxltltendlltltendl //Line 7
  • coutltltsetprecision(2) //Line 8
  • coutltltsetw(6)ltltaltltsetw(6)ltlty
  • ltltsetw(6)ltltxltltendl //Line 9
  • coutltltsetw(6)ltltxltltsetw(6)ltlta
  • ltltsetw(6)ltltyltltendlltltendl //Line 10
  • coutltltsetw(5)ltltaltltxltltendl //Line 11
  • coutltltsetw(2)ltltaltltsetw(4)ltltxltltendl //Line 12
  • return 0

56
  • Output
  • 12345678901234567890
  • 19
  • 345 Hi 19
  • 345 76.38 19
  • 19 345 76.38
  • 34519
  • 345 19

57
  • 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
  • ostreamVar.fill(ch)
  • where ostreamVar is an output stream variable
    and ch is a character. For example, the statement
  • cout.fill('')
  • sets the filling character to '' on the standard
    output screen.

58
  • The syntax to use the manipulator setfill is
  • ostreamVarltltsetfill(ch)
  • where ostreamVar is an output stream variable and
    ch is a character.
  • The statement
  • coutltltsetfill('')
  • sets the filling character to ''.

59
  • Example 3.9
  • //Example fill and setfill
  • include ltiostreamgt
  • include ltiomanipgt
  • using namespace std
  • int main()
  • int x 15 //Line 1
  • int y 7634 //Line 2
  • coutltlt"12345678901234567890"ltltendl //Line 3
  • coutltltsetw(5)ltltxltltsetw(7)ltlty
  • ltltsetw(8)ltlt"Warm"ltltendl //Line 4

60
  • coutltltsetw(5)ltltxltltsetw(7)ltltsetfill('')
  • ltltyltltsetw(8)ltlt"Warm"ltltendl //Line 7
  • coutltltsetw(5)ltltsetfill('_at_')ltltx
  • ltltsetw(7)ltltsetfill('')ltlty
  • ltltsetw(8)ltltsetfill('')ltlt"Warm"
  • ltltendl //Line 8
  • cout.fill(' ') //Line 9
  • coutltltsetw(5)ltltxltltsetw(7)ltlty
  • ltltsetw(8)ltlt"Warm"ltltendl //Line 10
  • return 0
  • Output
  • 12345678901234567890
  • 15 7634 Warm
  • 157634Warm
  • 157634Warm
  • _at__at__at_157634Warm

61
  • The left and right Manipulators
  • To left-justify the output, you use the
    manipulator left.
  • The syntax to set the manipulator left is
  • ostreamVarltltleft
  • where ostreamVar is an output stream variable.
  • The following statement sets the output to be
    left-justified on the standard output device
  • coutltltleft

62
  • You can disable the manipulator left by using the
    stream function unsetf. The syntax to disable the
    manipulator left is
  • ostreamVar.unsetf(iosleft)
  • where ostreamVar is an output stream variable.
    Disabling the manipulator left returns the output
    to the settings of the default output format.
  • The following statement disables the manipulator
    left on the standard output device
  • cout.unsetf(iosleft)

63
  • The syntax to set the manipulator right is
  • ostreamVarltltright
  • where ostreamVar is an output stream variable.
  • The following statement sets the output to be
    right-justified on the standard output device
  • coutltltright

64
  • Example 3-10
  • //Example left justification
  • include ltiostreamgt
  • include ltiomanipgt
  • using namespace std
  • int main()
  • int x 15 //Line 1
  • int y 7634 //Line 2
  • coutltltleft //Line 3
  • coutltlt"12345678901234567890"ltltendl //Line 4
  • coutltltsetw(5)ltltxltltsetw(7)ltlty
  • ltltsetw(8)ltlt"Warm"ltltendl //Line 5

65
  • coutltltsetw(5)ltltxltltsetw(7)ltlty
  • ltltsetw(8)ltlt"Warm"ltltendl //Line 7
  • coutltltsetw(5)ltltxltltsetw(7)ltltsetfill('')ltlty
  • ltltsetw(8)ltlt"Warm"ltltendl //Line 8
  • coutltltsetw(5)ltltsetfill('_at_')ltltx
  • ltltsetw(7)ltltsetfill('')ltlty
  • ltltsetw(8)ltltsetfill('')ltlt"Warm"ltltendl
    //Line 9
  • cout.unsetf(iosleft) //Line 10
  • cout.fill(' ') //Line 11
  • coutltltsetw(5)ltltxltltsetw(7)ltlty
  • ltltsetw(8)ltlt"Warm"ltltendl //Line 12
  • return 0

66
  • Output
  • 12345678901234567890
  • 15 7634 Warm
  • 157634Warm
  • 157634Warm
  • 15_at__at__at_7634Warm
  • 15 7634 Warm

67
  • 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.

68
  • 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.
  • The syntax to use the flush function is
  • ostreamVar.flush()
  • where ostreamVar is an output stream variable,
    such as cout.
  • 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
  • coutltltflush

69
  • Example 3-11
  • Consider the following statements in which num is
    an int variable
  • coutltlt"Enter an integer " //Line 1
  • cingtgtnum //Line 2
  • coutltltendl //Line 3
  • The statement at Line 1 outputs the following
    text
  • Enter an integer
  • After outputting this line, the cursor stays
    positioned after the colon.
  • The output of the statement at Line 1 first goes
    to the buffer.
  • If the buffer is not full, this line of text
    might not be displayed.
  • You could put the manipulator endl at the end of
    the statement at Line 1. However, by doing so,
    after printing the line of text, the cursor is
    positioned at the beginning of the next line.

70
  • The user is prompted to enter the number in the
    following line
  • Suppose that the statement at Line 1 is replaced
    by the following statement
  • coutltlt"Enter an integer "ltltflush //Line 1
  • In this case, the line of text,
  • Enter an integer
  • is displayed on the standard output device even
    if the buffer is not full. Moreover, after
    outputting the line of text, the cursor stays
    positioned after the colon the user will then
    enter the number after the colon.

71
  • To use stream functions such as get, ignore,
    fill, clear, and setf in a program, the program
    must include the header file iostream.
  • There are two types of manipulators those with
    parameters and those without parameters.
  • Manipulators with parameters are called
    parameterized stream manipulators.
  • Manipulators such as setprecision, setw, setfill,
    and setiosflags are parameterized.
  • Manipulators such as endl, fixed, scientific,
    showpoint, and left are without parameters.
  • Because flush can also be used as a manipulator
    without any arguments, flush is a manipulator
    without parameters, too.

72
  • To use a parameterized stream manipulatorthat
    is, a stream manipulator with parametersin a
    program, you must include the header file
    iomanip.
  • Manipulators without parameters are part of the
    iostream header file and, therefore, do not
    require inclusion of the header file iomanip.

73
  • 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.

74
  • If the input is
  • Alice Wonderland
  • the value of the variable name after the
    following statement executes is "Alice"
  • cingtgtname
  • 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'.

75
  • 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.
  • 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?"

76
  • 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.

77
  • 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.

78
(No Transcript)
79
  • Suppose declaration of Step 2.
  • Suppose that the input data is stored in a file
    called prog.dat on a floppy disk in drive A.
  • Save the output in a file called prog.out on a
    floppy disk in drive A.
  • The following statements associate inData with
    prog.dat and outData with prog.out.
  • inData.open("Aprog.dat") //open input file
  • outData.open("Aprog.out") //open output file

80
  • Step 4
  • 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.

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

82
  • 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

83
  • PROGRAMMING EXAMPLE MOVIE TICKET SALE AND
    DONATION TO CHARITY
  • A movie in a local theater is in great demand. To
    help a local charity, the theater owner has
    decided to donate a portion of the gross amount
    generated from the movie to the charity. This
    example designs and implements a program that
    prompts the user to input the movie name, adult
    ticket price, child ticket price, number of adult
    tickets sold, number of child tickets sold, and
    percentage of the gross amount to be donated to
    the charity. The output of the program is as
    follows.
  • -------------------------
    ---
  • Movie Name ....................... Duckey Goes
    to Mars
  • Number of Tickets Sold ........... 2650
  • Gross Amount ..................... 9150.00
  • Percentage of Gross Amount Donated 10.00
  • Amount Donated ................... 915.00
  • Net Sale ......................... 8235.00

84
  • Input
  • The input to the program consists of the movie
    name, adult ticket price, child ticket price,
    number of adult tickets sold, number of child
    tickets sold, and percentage of the gross amount
    to be donated to the charity.
  • Output
  • The output is as shown above.

85
  • Problem Analysis and Algorithm Design
  • grossAmount adultTicketPrice
    noOfAdultTicketsSold
  • childTicketPrice noOfChildTicketsSold
  • The formulas to calculate the amount donated and
    the net sale amount are given below.
  • 1. Get the movie name.
  • 2. Get the price of an adult ticket price.
  • 3. Get the price of a child ticket price.
  • 4. Get the number of adult tickets sold.
  • 5. Get the number of child tickets sold.
  • 6. Get the percentage of the gross amount donated
    to the charity.

86
  • 7. Calculate the gross amount using the following
    formula
  • grossAmount adultTicketPrice
    noOfAdultTicketsSold
  • childTicketPrice
    noOfChildTicketsSold
  • 8. Calculate the amount donated to the charity
    using the following formula
  • amountDonated grossAmount percentDonation
    / 100
  • 9. Calculate the net sale amount using the
    following formula
  • netSale grossAmount amountDonated

87
  • Variables
  • string movieName
  • double adultTicketPrice
  • double childTicketPrice
  • int noOfAdultTicketsSold
  • int noOfChildTicketsSold
  • double percentDonation
  • double grossAmount
  • double amountDonated
  • double netSaleAmount

88
  • Formatting Output
  • In the output, the first column is left-justified
    and the numbers in the second column are
    right-justified.
  • When printing a value in the first column, the
    manipulator left is used before printing a value
    in the second column, the manipulator right is
    used.
  • The empty space between the first and second
    columns is filled with dots the program uses the
    manipulator setfill to accomplish this goal.
  • In the lines showing the gross amount, amount
    donated, and net sale amount, the space between
    the sign and the number is filled with blank
    spaces.
  • Before printing the dollar sign, the program uses
    the manipulator setfill to set the filling
    character to blank.

89
  • The following statements accomplish the desired
    output
  • coutltlt"---------------"
  • ltlt"-------------"ltltendl
  • coutltltsetfill('.')ltltleftltltsetw(35)ltlt"Movie Name
    "
  • ltltrightltlt" "ltltmovieNameltltendl
  • coutltltleftltltsetw(35)ltlt"Number of Tickets Sold "
  • ltltsetfill(' ')ltltrightltltsetw(10)
  • ltltnoOfAdultTicketsSold noOfChildTicketsSold
  • ltltendl
  • coutltltsetfill('.')ltltleftltltsetw(35)ltlt"Gross
    Amount "
  • ltltsetfill(' ')ltltrightltlt" "
  • ltltsetw(8)ltltgrossAmountltltendl
  • coutltltsetfill('.')ltltleftltltsetw(35)
  • ltlt"Percentage of Gross Amount Donated "
  • ltltsetfill(' ')ltltright
  • ltltsetw(9)ltltpercentDonationltlt''ltltendl

90
  • coutltltsetfill('.')ltltleftltltsetw(35)ltlt"Amount
    Donated "
  • ltltsetfill(' ')ltltrightltlt" "
  • ltltsetw(8)ltltamountDonatedltltendl
  • coutltltsetfill('.')ltltleftltltsetw(35)ltlt"Net Sale "
  • ltltsetfill(' ')ltltrightltlt" "
  • ltltsetw(8)ltltnetSaleAmountltltendl

91
  • Main Algorithm
  • 1. Declare the variables.
  • 2. Set the output of the floating-point numbers
    to two decimal places in a fixed decimal format
    with a decimal point and trailing zeros.
    Therefore, you need to include the header file
    iomanip.
  • 3. Prompt the user to enter a movie name.
  • 4. Input (read) the movie name. Because the name
    of a movie might contain more than one word (and,
    therefore, might contain blanks), the program
    uses the function getline to input the movie
    name. Moreover, because the function getline also
    reads the newline character, after entering the
    movie name on a line, you need to press the Enter
    key twice.
  • 5. Prompt the user to enter the price of an adult
    ticket.
  • 6. Input (read) the price of an adult ticket.
  • 7. Prompt the user to enter the price of a child
    ticket.

92
  • 8. Input (read) the price of a child ticket.
  • 9. Prompt the user to enter the number of adult
    tickets sold.
  • 10. Input (read) the number of adult tickets
    sold.
  • 11. Prompt the user to enter the number of child
    tickets sold.
  • 12. Input (read) the number of child tickets
    sold.
  • 13. Prompt the user to enter the percentage of
    the gross amount donated.
  • 14. Input (read) the percentage of the gross
    amount donated.
  • 15. Calculate the gross amount.
  • 16. Calculate the amount donated.
  • 17. Calculate the net sale amount.
  • 18. Output the results.

93
  • include ltiostreamgt
  • include ltiomanipgt
  • include ltstringgt
  • using namespace std
  • int main()
  • //Step 1
  • string movieName
  • double adultTicketPrice
  • double childTicketPrice
  • int noOfAdultTicketsSold
  • int noOfChildTicketsSold
  • double percentDonation
  • double grossAmount
  • double amountDonated
  • double netSaleAmount

94
  • coutltltfixedltltshowpointltltsetprecision(2)
    //Step 2
  • coutltlt"Enter movie name "ltltflush //Step 3
  • getline(cin,movieName) //Step 4
  • coutltltendl
  • coutltlt"Enter the price of an adult ticket
    "ltltflush //Step 5
  • cingtgtadultTicketPrice //Step 6
  • coutltltendl
  • coutltlt"Enter the price of a child ticket
    "ltltflush //Step 7
  • cingtgtchildTicketPrice //Step 8
  • coutltltendl

95
  • coutltlt"Enter number of adult tickets sold
    "ltltflush //Step 9
  • cingtgtnoOfAdultTicketsSold //Step 10
  • coutltltendl
  • coutltlt"Enter number of child tickets sold
    "ltltflush //Step 11
  • cingtgtnoOfChildTicketsSold //Step 12
  • coutltltendl
  • coutltlt"Enter the percentage of donation
    "ltltflush //Step 13
  • cingtgtpercentDonation //Step 14
  • coutltltendlltltendl
  • grossAmount adultTicketPrice
    noOfAdultTicketsSold
  • childTicketPrice noOfChildTicketsSold
  • //Step 15

96
  • amountDonated grossAmount percentDonation /
    100 //Step 16
  • netSaleAmount grossAmount - amountDonated
    //Step 17
  • //Step 18 Output results
  • coutltlt"---------------"
  • ltlt"-------------"ltltendl
  • coutltltsetfill('.')ltltleftltltsetw(35)ltlt"Movie
    Name "
  • ltltrightltlt" "ltltmovieNameltltendl
  • coutltltleftltltsetw(35)ltlt"Number of Tickets Sold
    "
  • ltltsetfill(' ')ltltrightltltsetw(10)
  • ltltnoOfAdultTicketsSold noOfChildTicketsSold
  • ltltendl

97
  • coutltltsetfill('.')ltltleftltltsetw(35)ltlt"Gross
    Amount "
  • ltltsetfill(' ')ltltrightltlt" "
  • ltltsetw(8)ltltgrossAmountltltendl
  • coutltltsetfill('.')ltltleftltltsetw(35)
  • ltlt"Percentage of Gross Amount Donated "
  • ltltsetfill(' ')ltltright
  • ltltsetw(9)ltltpercentDonationltlt''ltltendl
  • coutltltsetfill('.')ltltleftltltsetw(35)ltlt"Amount
    Donated "
  • ltltsetfill(' ')ltltrightltlt" "
  • ltltsetw(8)ltltamountDonatedltltendl
  • coutltltsetfill('.')ltltleftltltsetw(35)ltlt"Net Sale
    "
  • ltltsetfill(' ')ltltrightltlt" "
  • ltltsetw(8)ltltnetSaleAmountltltendl
  • return 0

98
  • Sample Run (In this sample run, the user input
    is in red)
  • Enter movie name Duckey Goes to Mars
  • Enter the price of an adult ticket 4.50
  • Enter the price of a child ticket 3.00
  • Enter number of adult tickets sold 800
  • Enter number of child tickets sold 1850
  • Enter the percentage of donation 10
  • -------------------------
    ---
  • Movie Name ....................... Duckey Goes
    to Mars
  • Number of Tickets Sold ........... 2650

99
  • PROGRAMMING EXAMPLE STUDENT GRADE
  • Write a program that reads a student ID followed
    by five test scores. The program should output
    the student ID, the five test scores, and the
    average test score. Output the average test score
    with two decimal places. Assume that the student
    ID is a character.
  • The data to be read is stored in a file called
    test.txt, and the file is stored on a floppy disk
    in drive A. The output should be stored in a
    file called testavg.out, and the output file
    should be stored on the floppy disk in drive A.
  • Input A file containing the student ID and five
    test scores.
  • Output The student ID, five test scores and the
    average of the five test scores. The output is to
    be saved in a file.

100
  • Problem Analysis and Algorithm Design
  • To find the average of five test scores, first we
    add the five test scores and then divide the sum
    by 5. Now, the input data is in the form student
    ID followed by five test scores. Therefore, we
    first read the student ID and then the five test
    scores. This discussion translates in the
    following algorithm
  • 1. Read student ID and the five test score.
  • 2. Output student ID and five test scores.
  • 3. Calculate the average.
  • 4. Output the average.
  • We will output the average test score in the
    fixed decimal format with two decimal places.

101
  • Variables
  • ifstream inFile //input file stream variable
  • ofstream outFile //output file stream variable
  • int test1, test2, test3, test4, test5 //
    variables
  • //to read five test scores
  • double average //variable to store average
  • //test score
  • char studentId //variable to store
  • //student ID

102
  • Main Algorithm
  • 1. Declare the variables.
  • 2. Open the input file.
  • 3. Open the output file.
  • 4. To output the floating-point numbers in a
    fixed decimal format with a decimal point and
    trailing zeros, set the manipulators fixed and
    showpoint. Also, to output the floating-point
    numbers with two decimal places, set the
    precision to two decimal places.
  • 5. Read the student ID.
  • 6. Output the student ID.
  • 7. Read the five test scores.
  • 8. Output the five test scores.
  • 9. Find the average test score.
  • 10. Output the average test score.
  • 11. Close the input and output files.

103
  • //Program to calculate average test score.
  • include ltiostreamgt
  • include ltfstreamgt
  • include ltiomanipgt
  • using namespace std
  • int main()
  • //Declare variables Step 1
  • ifstream inFile //input file stream variable
  • ofstream outFile //output file stream variable
  • int test1, test2, test3, test4, test5
  • double average
  • char studentId

104
  • inFile.open("atest.txt") //Step 2
  • outFile.open("atestavg.out") //Step 3
  • outFileltltfixedltltshowpoint //Step 4
  • outFileltltsetprecision(2) //Step 4
  • coutltlt"Processing data"ltltendl
  • inFilegtgtstudentId //Step 5
  • outFileltlt"Student ID "ltltstudentId
  • ltltendl //Step 6
  • inFilegtgttest1gtgttest2gtgttest3
  • gtgttest4gtgttest5 //Step 7

105
  • outFileltlt"Test scores "ltltsetw(4)ltlttest1
  • ltltsetw(4)ltlttest2ltltsetw(4)ltlttest3
  • ltltsetw(4)ltlttest4
  • ltltsetw(4)ltlttest5ltltendl //Step 8
  • average static_castltdoublegt(test1test2test3
  • test4test5)/5.0 //Step 9
  • outFileltlt"Average test score "ltltsetw(6)
  • ltltaverageltltendl //Step 10
  • inFile.close() //Step 11
  • outFile.close() //Step 11
  • return 0

106
  • Sample Run
  • Input File (contents of the file atest.txt)
  • T 87 89 65 37 98
  • Output File (contents of the file atestavg.out)
  • Student ID T
  • Test scores 87 89 65 37 98
  • Average test score 75.20
Write a Comment
User Comments (0)
About PowerShow.com