• No results found

OBJECTIVES In this chapter we develop problem solutions containing:

2.5 Standard Input and Output

C++ uses the object cin (pronounced “see in”) to perform standard input and the object cout(pronounced “see out”) to perform standard output. These objects are defined in the Standard C++ library file iostream. To use either of these objects in a program, we must include the following preprocessor directive:

#include <iostream>

The cout Object

The cout object is defined to stream output to the standard output device. The word stream stream

suggests a continual stream of characters that is generated by the program and sent to an output buffer. When the output buffer is filled, the contents are displayed on the standard output buffer

output device. For our examples, we will assume that the standard output device is the screen.

Standard Output: C++ uses the ostream object cout to stream the value of an expres-sion to standard output. cout is defined in the header file iostream. To use cout a program must include the compiler directive #include <iostream>.

Syntax

cout << expression << expression;

Example

cout << "The radius is "<< radius << " centimeters\n";

62 Chapter 2 Simple C++ Programs

The operator is used with cout to output a value to the screen. The following state-ment outputs three values to the screen:

cout << "The radius of the circle is "

<< radius << " centimeters\n";

Each value to be output must be preceded by the operator. In the foregoing example, the first value to be output is the literal string “The radius of the circle is ”, the second value to be output is the value of the object radius, the third value to be output is the string “ centimeters

\n”. The characters (\n) represent the newline character; the newline character causes an newline

advance to a new line on the screen when printed. The following example illustrates the use of cout:

double radius(10), area;

const double PI = acos(-1.0);

cout << "The radius of the circle is: " << radius

<< " centimeters\n"

<< "The area is " << PI*radius*radius

<< " square centimeters\n";

The output from these statements is:

The radius of the circle is: 10 centimeters The area is 3.14159 square centimeters

Notice that no decimal point is displayed in the value of radius, even though radius is declared to be of type double. Although this is the default format for printing floating point values in C++, we can overide this format using stream functions and manipulators.

Stream Objects

The identifier cout is declared to be an object of type ostream and is defined by the com-piler to stream data to standard output. The ostream class includes methods, also referred to as member functions. Member functions are defined within a class definition, and can be member functions

called only by objects of the same class type. Since cout is an object of type ostream the coutobject can call member functions of the ostream class to set the state of the format flags associated with standard output. The format flags are data members of the ostream class.

A special operator called the dot operator (.) is used when an object calls one of its member dot operator (.)

functions. The following program uses two member functions of the ostream class to set the desired format for streaming floating point values to standard output. The setf() member function is used to set the format for displaying a floating point value to fixed form, or decimal form. The member function precision() is used to set the number of significant digits that should be displayed to the right of the decimal point.

/*---*/

/* Program chapter2_4 */

/* */

/* This program computes area of a circle. */

/* Results are displayed with two digits */

/* to the right of the decimal point. */

Section 2.5 Standard Input and Output 63

#include<iostream> //Required for cout, setf() and precision().

#include<cmath> //Required for acos().

using namespace std;

const double PI = acos(-1.0);

int main() {

//Declare and initialize objects.

double radius(10), area;

area = PI*radius*radius;

//Call the setf member function using dot operator.

cout.setf(ios::fixed); //Fixed form(xx.xx).

//Call the precision member function using dot operator.

cout.precision(2); //Display 2 digits to right of decimal.

cout << "The radius of the circle is: " << radius

<< " centimeters\nThe area is "

<< area << " square centimeters\n";

//exit program return 0;

}

/*---*/

The output from this program is

The radius of the circle is: 10.00 centimeters The area is 314.16 square centimeters

When a format flag is set by a call to setf() the flag remains set until it is changed by another call to setf(), or is unset (reset to zero) by a call to the stream function unsetf(). Table 2.6 lists just a few of the format flags defined in the ios class. The value ios::showpoint, for example, refers to the identifier showpoint defined in the ios class.

When cout calls setf() with a value of ios::showpoint, as in the statement cout.setf(ios::showpoint);

TABLE 2.6 Common Format Flags

Flag Meaning

ios::showpoint display the decimal point ios::fixed decimal notation ios::scientific scientific notation ios::right print right justified ios::left print left justified

64 Chapter 2 Simple C++ Programs

the state of the showpoint flag associated with the cout object is set to true and all floating point values streamed to standard output will be displayed with a decimal point. The state-ment

cout.unsetf(ios::showpoint);

would result in setting the state of the showpoint flag back to false (or zero) and restoring the default formatting for displaying floating point values to standard output.

The member function precision() specifies the number of significant digits to be displayed for floating point values, and its behavior is dependent on the state of other format flags. For example, when cout calls precision(2) after setting the state of the format flag to fixed, the integer argument 2 specifies that two digits should be displayed to the right of the decimal point, as illustrated in program chapter2_4. If cout calls precision(2) after setting the state of the format flag to scientific, the integer argument 2 specifies that a total of two significant digits should be displayed.

Modify!

1. Create a file containing the program chapter2_4 discussed in this section. Run the program

The radius of the circle is: 10.00 centimeters The area is 314.16 square centimeters

2. Replace the setf() statement in program chapter2_4 with the statement cout.setf(ios::scientific);

Compile and run the modified program. How did the output change? Explain.

3. Replace the setf() statement in program chapter2_4 with the statement cout.setf(ios::showpoint);

Compile and run the modified program. How did the output change? Explain.

Manipulators

In program chapter2_4 we used stream functions to control the formatting of output printed to the screen. The formatting of output can also be controlled with the use of manipulators. A manipulator is a predefined object that can affect the state of an output manipulators

stream. Program chapter2_5 illustrates the use of manipulators instead of stream func-tions to control the formatting of the standard output stream. To use manipulators, a program must include the header file <iomanip>

/*---*/

/* Program chapter2_5 */

/*

/* This program computes area of a circle. */

Section 2.5 Standard Input and Output 65

/* Results are diplayed with two digits */

/* to the right of the decimal point. */

#include <iostream> //Required for cout, endl.

#include <iomanip> //Required for setw() setprecision(), fixed.

#include <cmath> //Required for acos().

using namespace std;

const double PI = acos(-1.0);

int main() {

//Declare and initialize objects, double radius(10), area;

area = PI*radius*radius;

cout << fixed << setprecision(2);

cout << "The radius of the circle is: "

<< setw(10) << radius << " centimeters" << endl;

cout << "The area of the circle is: " << setw(10) << area

<< " square centimeters" << endl;

//exit program return 0;

}

/*---*/

The output from this program is:

The radius of the circle is: 10.00 centimeters The area of the circle is: 314.16 square centimeters

The manipulator endl is defined in the header file <iostream>, and is used in program chapter2_5to advance to the beginning of a new line. The endl manipulator sends a newline character (‘\n’) to standard output and it immediately flushes the output buffer, rather than waiting until the output buffer is full.When cout statements are used to print memory snapshots of a program for debugging, the endl manipulator should be used (in place of\n) to ensure that the output buffer is flushed and you see your output before the next statement is executed.

The manipulators fixed and setprecision() are used to set the form and preci-sion for displaying floating point values. Notice that manipulators are not member functions and thus they are not called using the dot operator. However, they have the same affect on the state of the format flags as the stream functions used in program chapter2_4. The manipu-lator setw() is used to specify a width, or number of columns, to be used for displaying the next value sent to the output buffer. The setw() manipulator is useful when results need to be printed in a table format. Table 2.7 lists several of the commonly used manipulators defined in the header file iomanip. To use these manipulators, a program must #include the file

<iomanip>.

66 Chapter 2 Simple C++ Programs

TABLE 2.7 Common Manipulators

Manipulator Meaning

showpoint display the decimal point

fixed decimal notation

scientific scientific notation

setprecision(n) set the number of significant digits to be printed to the integer value n

setw(n) set the minimum number of columns for printing the next value to the integer value n

right print right justified left print left justified

Practice!

Assume that the integer object sum contains the value 150 and that the double object averagecontains the value 12.368 and that the header files iomanip and iostream have been included. Show the output generated by the following code segments. Assume each is an independent code segment.

1. cout << sum << " " << average;

2. cout << sum;

cout << average;

3. cout << sum << endl << average;

4. cout.precision(2);

cout << sum << endl << average;

5. cout.setf(ios::showpoint);

cout.precision(3);

cout << sum << ',' << average;

6. cout.setf(ios::fixed);

cout.setf(ios::showpoint);

cout.precision(3);

cout << sum << ',' << average;

7. cout << setprecision(2) << sum << endl << average;

8. cout << fixed << setprecision(3)

<< setw(10) << average << endl << setw(10)

<< sum << endl;

Section 2.5 Standard Input and Output 67

The cin Object

The cin object is an object of type istream and is defined by the compiler to stream input from the standard input device. For our examples we will assume the standard input device is the keyboard.

Standard Input: C++ uses the istream object cin to stream data from standard input and store values in memory locations named by the identifiers. cin is defined in the header file iostream. To use cin, a program must include the compiler directive #include

<iostream>.

Syntax

cin >> identifier >> identifier >> identifer;

Example

cin >> x >> y >> count;

The input operator >> is used with cin to input a value from the keyboard and assign the value to a variable. The >> operator uses whitespace (blanks, tabs, newlines) as delimiters, or separators, for values on the input stream and so the >> operator discards all whitespace.

The following statement inputs three values from the keyboard.

cin >> var1 >> var2 >> var3;

In the statement above, the first value typed at the keyboard will be assigned to the variable var1, the second value to var2 and the third value to var3. When a cin statement is executed, the program waits for input. A cout statement usually precedes a cin statement to prompt the user to enter data. A prompt is text printed to the screen to describe to the user prompt

the order and data type of the values that are to be entered from the keyboard.

The data entered from the keyboard is stored in an input buffer and is not actually sent to the program until the< Enter > key is hit. This allows the user to backspace and make corrections while entering data.

Numeric data typed at the keyboard should be separated by whitespace, but it does not matter how many whitespace characters are used. The>> operator will continue to discard whitespace until it receives values for each of the identifiers in the statement. The values entered from the keyboard must be compatible with the data type of the identifiers in the cin statement.Potential input errors will be discussed in Chapter 5.

The following example illustrates the use of cin:

#include <iostream> //Required for cin using namespace std;

int main() {

double rate, hours;

int id;

char code;

68 Chapter 2 Simple C++ Programs

// Prompt user for input

cout << "Enter the floating point rate of pay "

<< "and hours worked: ";

cin >> rate >> hours;

cout << "Enter the employee's integer id: ";

cin >> id;

cout << "Enter the tax code (h,r,l): "

cin >> code;

cout << rate << endl << hours << endl

<< id << endl << code << endl;

return0;

}

If the input stream from the keyboard contained the three lines of input 10.5 40

556 r

the objects in the input statement would be assigned values as shown in the following memory snapshot:

double rate 10.5 double hours 40

int id 556 char code 'r'

The cout statement would print the following output to the screen:

10.5 40 556 r

The operator discards whitespace and interprets the input value according to the data type of the identifier that follows. For some applications requiring character data, it may not be desirable to discard whitespace. The function get() is a member function of the istream class and can be called by cin to get a single character from the input stream. The statements char ch;

cin.get(ch);

will read the next character from the keyboard and assign the character to the variable ch. The get()function does not discard whitespace, but rather treats whitespace as valid character data, as illustrated in the following example:

char ch1, ch2, ch3;

cout << "Enter three characters: ";

cin.get(ch1);

cin.get(ch2);

cin.get(ch3);

cout << ch1 << ch2 << ch3;

If the input stream from the keyboard contained the two lines a

1

Section 2.6 Building C++ Solutions with IDEs: NetBeans 69 the objects ch1, ch2, and ch3 would be assigned values as shown in the following memory snapshot:

char ch1 'a' char ch2 '\n' char ch3 '1'

The output would be a

1

The get() function treats whitespace as valid character data; thus, the newline character was input from the keyboard, stored in the object ch2 and printed to the screen in the cout statement.

2.6 Building C++ Solutions with IDEs: NetBeans

We have discussed the general structure of a C++ program and written several simple pro-grams to illustrate the use of data types, arithmetic operators, and input and output operators.

In this section, we will illustrate how to develop a C++ solution using an Integrated De-velopment Environment (IDE). An IDE is a software package designed to facilitate the IDE

development of software solutions. IDEs include an editor, a compiler, a debugger, and many additional tools to aide in the design and development of large software solutions. As with most software packages, there is a learning curve, and it takes time and experience to be-come a productive user of an IDE. In this section, we will develop a C++ solution for program chapter1_1using NetBeans. Developing C++ solutions with NetBeans is presented again in Chapter 3, and the MS Visual C++ Express IDE is presented in Chapter 4.

NetBeans

The NetBeans IDE is an open source project that provides a development environment for multiple languages including Java, C and C++. When the NetBeans application is launched, a welcome screen appears as shown below:

70 Chapter 2 Simple C++ Programs

We will work through a simple example to illustrate the use of the editor and compiler in NetBeans. Notice that NetBeans provides a Quick Start Tutorial. We recommend that you view this tutorial to learn how to become a more productive user of the IDE.

To create a new C++ solution, we must first create a new NetBeans project. Select New Project... from the File menu at the top of the NetBeans window. A New Project screen will appear, similar to the one shown below.

For this C++ project, we will select C/C++ from the Categories: menu, then select C/C++ Application from the Projects: menu and click the Next> button at the bottom of the window. The following Project Name and Location window will appear.

Section 2.6 Building C++ Solutions with IDEs: NetBeans 71 Select the directory of your choice from the Browse... button, and name the project ProgramChapter1_1. Click on the Finish button to complete the creation of your Net-Beans project.

Recall that every C++ solution requires exactly one function named main. To create main we must add a new file to our project. To add a new file select New File... from the File menu. The following Choose File Type window will appear.

Select C++ Files from the Categories: menu and Main C++ File from the File Types:

menu, then click the Next > button on the bottom of the screen. A Name and Location window will appear, as shown below.

72 Chapter 2 Simple C++ Programs

Name the file main and click the Finish button at the bottom of the screen. A new file with the following content will be created within an editor window.

Notice that the header for main() has the parameters int argc, char** argv.

These optional parameters will be discussed later in the text. We will modify the main pro-gram by adding statements from propro-gram chapter1_1 found on page 28 of this text. The modified program is shown below.

Section 2.6 Building C++ Solutions with IDEs: NetBeans 73 To compile the program, select Build Main Project from the Run menu at the top of the NetBeans window. An output window will appear as shown below.

We see from the contents of the window that the build was successful, thus we can attempt to execute the program and view the results. To execute the program, choose Run Main Project from the Run menu. Our program executes and the output is displayed in a separate window, as shown below.

74 Chapter 2 Simple C++ Programs

74 Chapter 2 Simple C++ Programs