0% found this document useful (0 votes)
21 views40 pages

Input Failure in C++ Variable Types

This chapter discusses input and output in C++ programs. It covers input/output streams, standard input and output devices, and using the extraction operator (>>) to read data from the standard input stream (cin) into variables. Specifically, it explains that >> skips whitespace when reading and interprets data based on the variable type. The chapter also discusses detecting input failures if invalid data is entered.

Uploaded by

Althea Esperanza
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views40 pages

Input Failure in C++ Variable Types

This chapter discusses input and output in C++ programs. It covers input/output streams, standard input and output devices, and using the extraction operator (>>) to read data from the standard input stream (cin) into variables. Specifically, it explains that >> skips whitespace when reading and interprets data based on the variable type. The chapter also discusses detecting input failures if invalid data is entered.

Uploaded by

Althea Esperanza
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 3

Input/Output

C++ Programming: Program Design Including Data Structures, Eighth Edition

1
Objectives (1 of 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, putback, and peek

2
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 2
or otherwise on a password-protected website for classroom
Objectives (2 of 2)

• 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
• Learn how to debug logic errors
• Become familiar with file input and output

3
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 3
or otherwise on a password-protected website for classroom
I/O Streams and Standard I/O Devices (1 of 3)

• I/O: sequence of bytes (stream of bytes) from source to destination


• Bytes are usually characters, unless program requires other types of information
• Stream: sequence of characters from the source to the destination
• Input stream: sequence of characters from an input device to the computer
• Output stream: sequence of characters from the computer to an output device

4
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 4
or otherwise on a password-protected website for classroom
I/O Streams and Standard I/O Devices (2 of 3)

• Use iostream header file to receive data from keyboard and send output to
the screen
• Contains definitions of two data types:
- istream: input stream
- ostream: output stream
• Has two variables:
- cin: stands for common input
- cout: stands for common output

5
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 5
or otherwise on a password-protected website for classroom
I/O Streams and Standard I/O Devices (3 of 3)

• Variable declaration is similar to:


• istream cin;
• ostream cout;
• To use cin and cout, the preprocessor directive #include <iostream>
must be used
• Input stream variables: type istream
• Output stream variables: type ostream

6
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 6
or otherwise on a password-protected website for classroom
cin and the Extraction Operator >> (1 of 7)

• The syntax of an input statement using cin and the extraction operator >> is

• The extraction operator >> is binary


• Left-side operand is an input stream variable
- Example: cin
• Right-side operand is a variable

7
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 7
or otherwise on a password-protected website for classroom
cin and the Extraction Operator >> (2 of 7)

• No difference between a single cin with multiple variables and multiple cin
statements with one variable in each statement
cin >> payRate >> hoursWorked;

cin >> payRate;


cin >> hoursWorked;
• When scanning, >> skips all whitespace
• Blanks and certain nonprintable characters
• >> distinguishes between character 2 and number 2 by the right-side operand
of >>
• If type char or int (or double), the 2 is treated as a character or as a number 2,
respectively

8
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 8
or otherwise on a password-protected website for classroom
cin and the Extraction Operator >> (3 of 7)

TABLE 3-1 Valid Input for a Variable of the Simple Data Type

Data Type of a Valid Input for a


char One printable character except the blank.
int An integer, possibly preceded by a + or - sign.
A decimal number, possibly preceded by a + or - sign. If the actual
double data input is an integer, the input is converted to a decimal number
with the zero decimal part.

• Entering a char value into an int or double variable causes serious errors,
called input failure

9
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 9
or otherwise on a password-protected website for classroom
cin and the Extraction Operator >> (4 of 7)

• When reading data into a char variable


• >> skips leading whitespace, finds and stores only the next character
• Reading stops after a single character
• To read data into an int or double variable
• >> skips leading whitespace, reads + or - sign (if any), reads the digits (including
decimal for floating-point variables)
• Reading stops on whitespace or a non-digit character

10
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 10
or otherwise on a password-protected website for classroom
cin and the Extraction Operator >> (5 of 7)

11
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 11
or otherwise on a password-protected website for classroom
cin and the Extraction Operator >> (6 of 7)

12
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 12
or otherwise on a password-protected website for classroom
cin and the Extraction Operator >> (7 of 7)

13
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 13
or otherwise on a password-protected website for classroom
Using Predefined Functions in a Program (1 of 3)

• A function (subprogram) is a set of instructions


• When activated, it accomplishes a task
• main executes when a program is run
• Other functions execute only when called
• C++ includes a wealth of functions
• Predefined functions are organized as a collection of libraries called header files

14
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 14
or otherwise on a password-protected website for classroom
Using Predefined Functions in a Program (2 of 3)

• Header file may contain several functions


• To use a predefined function, you need the name of the appropriate header file
• You also need to know:
- Function name
- Number of parameters required
- Type of each parameter
- What the function is going to do

15
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 15
or otherwise on a password-protected website for classroom
Using Predefined Functions in a Program (3 of 3)

• To use pow (power), include cmath


• Two numeric parameters
• Syntax: pow(x,y) = xy
- x and y are the arguments or parameters
• In pow(2,3), the parameters are 2 and 3

16
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 16
or otherwise on a password-protected website for classroom
cin and the get Function

• The get function


• Inputs next character (including whitespace)
• Stores in memory location indicated by its argument
• The syntax of cin and the get function

• varChar is a char variable


- It is the argument (or parameter) of the function

17
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 17
or otherwise on a password-protected website for classroom
cin and the ignore Function (1 of 2)

• ignore function
• Discards a portion of the input
• The syntax to use the function ignore is:

• intExp is an integer expression


• chExp is a char expression
• If intExp is a value m, the statement says to ignore the next m characters or
all characters until the character specified by chExp

18
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 18
or otherwise on a password-protected website for classroom
cin and the ignore Function (2 of 2)

19
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 19
or otherwise on a password-protected website for classroom
The putback and peek Functions (1 of 2)

• putback function
• Places previous character extracted by the get function from an input stream back to
that stream
• peek function
• Returns next character from the input stream
• Does not remove the character from that stream

20
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 20
or otherwise on a password-protected website for classroom
The putback and peek Functions (2 of 2)

• Syntax for putback

• istreamVar: an input stream variable (such as cin)


• ch is a char variable
• Syntax for peek

• istreamVar: an input stream variable (such as cin)


• ch is a char variable

21
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 21
or otherwise on a password-protected website for classroom
The Dot Notation between I/O Stream Variables and I/O Functions: A
Precaution

• In the statement
[Link](ch);
cin and get are two separate identifiers separated by a dot
• Called the dot notation, the dot separates the input stream variable name from
the member, or function, name
• In C++, the dot is the member access operator

22
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 22
or otherwise on a password-protected website for classroom
Input Failure

• Things can go wrong during execution


• If input data does not match corresponding variables, the program may run into
problems
• Trying to read a letter into an int or double variable will result in an input
failure
• If an error occurs when reading data
• Input stream enters the fail state

23
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 23
or otherwise on a password-protected website for classroom
The clear Function

• Once in a fail state, all further I/O statements using that stream are ignored
• The program continues to execute with whatever values are stored in variables
• This causes incorrect results
• The clear function restores the input stream to a working state
• The syntax of the function clear is:

24
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 24
or otherwise on a password-protected website for classroom
Output and Formatting Output

• Syntax of cout when used with <<

• expression is evaluated
• value is printed
• manipulator is used to format the output
• Example: endl

25
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 25
or otherwise on a password-protected website for classroom
setprecision Manipulator

• Syntax

• Outputs decimal numbers with up to n decimal places


• Must include the header file iomanip
• #include <iomanip>

26
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 26
or otherwise on a password-protected website for classroom
fixed Manipulator

• fixed outputs floating-point numbers in a fixed decimal format


• Example: cout << fixed;
• Disable by using the stream member function unsetf
- Example: [Link](ios::fixed);

• scientific manipulator outputs floating-point numbers in scientific format

27
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 27
or otherwise on a password-protected website for classroom
showpoint Manipulator

• showpoint forces output to show the decimal point and trailing zeros
• Examples
• cout << showpoint;
• cout << fixed << showpoint;

28
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 28
or otherwise on a password-protected website for classroom
C++14 Digit Separator

• Reading and writing of long numbers can be error prone


• In C++, commas cannot be used to separate the digits of a number
• C++14 introduces digit separator ' (single-quote character)
• Example: 87523872918 can be represented as 87'523'872'918

29
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 29
or otherwise on a password-protected website for classroom
setw

• Outputs the value of an expression in a specified number of columns


• cout << setw(5) << x << endl;
• If number of columns exceeds the number of columns required by the
expression
• Output of the expression is right-justified
• Unused columns to the left are filled with spaces
• Must include the header file iomanip

30
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 30
or otherwise on a password-protected website for classroom
Additional Output Formatting Tools

• Additional formatting tools that give you more control over your output:
• setfill manipulator
• left and right manipulators
• unsetf manipulator

31
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 31
or otherwise on a password-protected website for classroom
setfill Manipulator

• Output stream variables can use setfill to fill unused columns with a
character

• Example:
• cout << setfill('#');

32
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 32
or otherwise on a password-protected website for classroom
left and right Manipulators

• left manipulator left-justifies the output

• Disable left by using unsetf

• right manipulator right-justifies the output

33
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 33
or otherwise on a password-protected website for classroom
Types of Manipulators

• Two types of manipulators


• Those with parameters

• Those without parameters


• Parameterized stream manipulators require the iomanip header
• setprecision, setw, and setfill
• Manipulators without parameters require the iostream header
• endl, fixed, scientific, showpoint, and left

34
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 34
or otherwise on a password-protected website for classroom
Input/Output and the string Type

• An input stream variable (such as cin) and >> operator can read a string into
a variable of the data type string
• The extraction operator:
• Skips any leading whitespace characters
• Stops reading at a whitespace character
• The function getline reads until end of the current line

35
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 35
or otherwise on a password-protected website for classroom
Debugging: Understanding Logic Errors and Debugging with cout
statements

• Syntax errors are reported by the compiler


• Logic errors are typically not caught by the compiler
• Spot and correct using cout statements
- Temporarily insert an output statement
• Correct the problem
• Remove output statement

36
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 36
or otherwise on a password-protected website for classroom
File Input/Output

• A file is an area in secondary storage to hold info


• File I/O is a five-step process
1. Include fstream header
2. Declare file stream variables
3. Associate the file stream variables with the input/output sources – referred to as
opening the files
4. Use the file stream variables with >>, <<, or other input/output functions
5. Close the files

37
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 37
or otherwise on a password-protected website for classroom
Quick Review (1 of 3)

• Stream: infinite sequence of characters from a source to a destination


• Input stream: from a source to a computer
• Output stream: from a computer to a destination
• cin: common input
• cout: common output
• To use cin and cout, include iostream header

38
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 38
or otherwise on a password-protected website for classroom
Quick Review (2 of 3)

• get reads data character-by-character


• ignore skips data in a line
• putback puts last character retrieved by get back to the input stream
• peek returns next character from input stream, but does not remove it
• Attempting to read invalid data into a variable causes the input stream to enter
the fail state

39
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 39
or otherwise on a password-protected website for classroom
Quick Review (3 of 3)

• The manipulators setprecision, fixed, showpoint, setw, setfill,


left, and right can be used for formatting output
• Include iomanip for the manipulators setprecision, setw, and
setfill
• Header fstream contains the definitions of ifstream and ofstream

40
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 40
or otherwise on a password-protected website for classroom

Common questions

Powered by AI

The key functions of an input stream in C++ include 'cin', 'get', 'ignore', 'putback', and 'peek'. The 'cin' function reads input from the standard input device and uses the extraction operator '>>' to read data and assign it to a variable. The 'get' function inputs the next character (including whitespace) and stops after that single character. The 'ignore' function discards a portion of the input by ignoring a specified number of characters or until a specified character is found. The 'putback' function places the previous character extracted by the get function back to the input stream, and the 'peek' function returns the next character from the input stream without removing it .

Input failure in C++ occurs when invalid data is read into a variable, such as entering a char value into an int or double variable, causing the input stream to enter a fail state. Handling input failure typically involves checking the fail state of the input stream and using methods like 'cin.clear()' to clear the stream state and 'cin.ignore()' to discard erroneous input .

Both 'cin >>' and 'cin.get()' are used to read input in C++. 'cin >>' skips leading whitespaces and reads data based on the right-side variable's data type until whitespace or a non-digit is encountered. It can read multiple types per input line. In contrast, 'cin.get()' reads one character at a time, including whitespace, and stores it in the provided char variable. The key difference lies in their handling of whitespace and single character reading. Both are fundamental for input operations but are employed based on the specific input requirements .

Header files in C++ play a critical role by declaring the functions, classes, and objects necessary for various operations. They enable program functionality by specifying the interfaces to libraries. For I/O operations, the 'iostream' header provides definitions for 'cin', 'cout', 'istream', and 'ostream', facilitating input and output operations. Similarly, for predefined functions, including headers like 'cmath' grants access to mathematical functions such as 'pow'. This modularity supports code organization, reuse, and consistency in handling different operational aspects .

Predefined functions in C++ improve program functionality by providing ready-to-use solutions for common tasks, saving developer time and ensuring reliability. To use these functions, developers need to include the appropriate header file that contains the function's declaration. Additionally, knowing the function name, the number of parameters, their types, and the function's purpose is necessary for proper implementation. For example, to use the 'pow' function for power calculations, the 'cmath' header needs to be included .

The extraction operator '>>' in C++ handles different data types by skipping leading whitespace. For a char, it stores the next non-whitespace character; for an int, it reads digits possibly preceded by '+' or '-'; and for a double, it reads digits including a decimal point. It distinguishes between characters and numbers based on the variable's data type on the right side of the extraction, and stops reading on whitespace or a non-digit character .

The 'putback' function in C++ is used to place the last character extracted by the 'get' function back into the input stream, allowing it to be read again. This is useful for un-reading characters that should be processed differently. The 'peek' function returns the next character in the input stream without removing it, enabling a look-ahead in the stream. These functions allow for more flexible input handling by offering control over the stream's read position .

Manipulators in C++ are used to format the output stream. They can be parameterized like 'setprecision', 'setw', and 'setfill' requiring the 'iomanip' header, or non-parameterized like 'endl', 'fixed', 'scientific', 'showpoint', 'left', and 'right' using the 'iostream' header. 'setfill' fills unused columns with a specified character, while 'left' and 'right' manage output justification. They enhance output readability and are particularly useful when displaying numerical data where precise formatting is required .

File input/output in C++ is a five-step process: 1) Include the 'fstream' header; 2) Declare file stream variables using 'ifstream' for input and 'ofstream' for output; 3) Open the files by associating the file stream variables with specific files; 4) Perform input/output operations using '>>', '<<', or other I/O functions; 5) Close the files to free resources and ensure all data is written properly .

Using 'fstream' is preferable over 'cin' and 'cout' when dealing with files for input/output operations because 'fstream' enables reading from and writing to files on disk, which is crucial for tasks like data persistence and batch processes. 'cin' and 'cout' are suitable for console-based interactions, such as user input and immediate outputs. 'fstream' is essential for applications needing to save data between sessions or process large datasets without direct user interaction, offering greater control and flexibility in handling input/output operations .

You might also like