1 / 29100%
Module 2
Basic Elements and I/O
A. The Basics of a C++ Program
A C++ program can contain various types of expressions such as arithmetic and
strings. For example, length + width is an arithmetic expression. Anything in double
quotes is a string. For example, "Program to compute and output the perimeter and " is a
string. Similarly, "area of a rectangle." is also a string. Typically, a string evaluates to
itself. Arithmetic expressions are evaluated according to rules of arithmetic operations,
which you typically learn in an arithmetic course. Later in this chapter, we will explain
how arithmetic expressions and strings are formed and evaluated.
Also note that in an output statement, endl causes the insertion point to move to
the beginning of the next line. (Note that in endl, the last letter is lowercase el. Also, on
the screen, the insertion point is where the cursor is.) Therefore, the preceding statement
causes the system to display the following line on the screen.
Next, let us note the following about the previous C++ program. A C++ program
is a collection of functions, one of which is the function main. Roughly speaking, a
function is a set of statements whose objective is to accomplish something. The preceding
program consists of only the function main; all C++ programs require the function main.
The first four lines of the program begins with the pair of symbols // (shown in green),
which are comments. Comments are for the user; they typically explain the purpose of
the programs, that is, the meaning of the statements.
Every C++ program has a function called main. Thus, if a C++ program has only
one function, it must be the function main. Until Chapter 6, other than using some of the
predefined functions, you will mainly deal with the function main. By the end of this
chapter, you will have learned how to write programs consisting only of the function
main. If you have never seen a program written in a programming language, the C++
program in Example 2-1 may look like a foreign language. To make meaningful
sentences in a foreign language, you must learn its alphabet, words, and grammar. The
same is true of a programming language. To write meaningful programs, you must learn
the programming languages special symbols, words, and syntax rules. The syntax rules
tell you which statements (instructions) are legal or valid, that is, which are accepted by
the programming language and which are not. You must also learn semantic rules, which
determine the meaning of the instructions. The programming languages rules, symbols,
and special words enable you to write programs to solve problems.
The program that you write should be clear not only to you, but also to the reader
of your program. Part of good programming is the inclusion of comments in the program.
Typically, comments can be used to identify the authors of the program, give the date
when the program is written or modified, give a brief explanation of the program, and
explain the meaning of key statements in a program. In the programming examples, for
the programs that we write, we will not include the date when the program is written,
consistent with the standard convention for writing such books. Comments are for the
reader, not for the compiler. So when a compiler compiles a program to check for the
syntax errors, it completely ignores comments.
The smallest individual unit of a program written in any language is called a
token. C++s tokens are divided into special symbols, word symbols, and identifiers. The
first row includes mathematical symbols for addition, subtraction, multiplication, and
division. The second row consists of punctuation marks taken from English grammar.
Note that the comma is also a special symbol. In C++, commas are used to separate items
in a list. Semicolons are also special symbols and are used to end a C++ statement. Note
that a blank, which is not shown above, is also a special symbol. You create a blank
symbol by pressing the space bar (only once) on the keyboard. The third row consists of
tokens made up of two characters that are regarded as a single symbol. No character can
come between the two characters in the token, not even a blank.
Every C++ program contains whitespaces. Whitespaces include blanks, tabs, and
newline characters. In a C++ program, whitespaces are used to separate special symbols,
reserved words, and identifiers. Whitespaces are nonprintable in the sense that when they
are printed on a white sheet of paper, the space between special symbols, reserved words,
and identifiers is white. Proper utilization of whitespaces in a program is important. They
can be used to make the program more readable.
B. Data Types
The data type char allows only one symbol to be placed between the single
quotation marks. Thus, the value abc is not of the type char. Furthermore, even though !=
and similar special symbols are considered to be one symbol, they are not regarded as
possible values of the data type char. All the individual symbols located on the keyboard
that are printable may be considered as possible values of the char data type. Several
different character data sets are currently in use. The most common are the American
Standard Code for Information Interchange (ASCII) and Extended BinaryCoded Decimal
Interchange Code (EBCDIC). The ASCII character set has 128 values. The EBCDIC
character set has 256 values and was created by IBM.
Each of the 128 values of the ASCII character set represents a different character.
For example, the value 65 represents A, and the value 43 represents +. Thus, each
character has a predefined ordering represented by the numeric value associated with the
character. This ordering is called a collating sequence, in the set. The collating sequence
is used when you compare characters. For example, the value representing B is 66, so A
is smaller than B. Similarly, + is smaller than A because 43 is smaller than 65. The 14th
character in the ASCII character set is called the newline character and is represented as
n. (Note that the position of the newline character in the ASCII character set is 13
because the position of the first character is 0.)
In programming, characters play a vital role in representing textual data and
controlling the flow of information within a program. Among the myriad characters
available, some hold special significance due to their unique functions and
representations. For instance, the newline character, denoted as n, serves as a crucial
element for formatting text by indicating the end of a line and moving the cursor to the
beginning of the next line. Despite being represented by a combination of two characters
(a backslash followed by the letter n), it is treated as a single character in programming
languages.
Similarly, the horizontal tab character, represented as t, is instrumental in
organizing text by creating consistent spacing between elements. When encountered in a
string, it instructs the program to advance the cursor to the next tab stop, typically aligned
at fixed intervals. This facilitates the alignment of text in tabular formats or indents in
code blocks, enhancing readability and visual structure.
Another noteworthy character is the null character, depicted as 0, which holds
particular significance in string manipulation and termination. In C++ and many other
programming languages, the null character serves as the sentinel value marking the end
of a string. When encountered in a character array, it signifies the termination point,
allowing functions to operate on strings effectively by iterating until the null character is
encountered.
Furthermore, the ASCII character set defines a range of characters, with the first
32 characters designated as nonprintable control characters. These characters, often
referred to as control codes or control characters, encompass a variety of functions,
including carriage return, vertical tab, and bell, among others. While these characters are
not directly printable, they exert control over peripheral devices, facilitate text
manipulation, and enable communication protocols.
Understanding the nuances of these special characters is essential for effective
programming, as they underpin fundamental operations such as text formatting, string
manipulation, and input/output processing. By leveraging these characters judiciously,
programmers can enhance the functionality, readability, and usability of their code,
resulting in more robust and user-friendly software applications.
In summary, special characters such as newline, horizontal tab, and null play
pivotal roles in text processing and control flow within programming languages. Despite
their seemingly simple representations, they wield significant influence over the behavior
and appearance of software applications. By mastering the usage of these characters,
programmers can unlock new possibilities for text manipulation, formatting, and
communication, thereby elevating the quality and effectiveness of their code.
C. Data Types, Variables, and Assignment Statements
One of the most important uses of a computer is its ability to calculate. You can
use the standard arithmetic operators to manipulate integral and floating-point data types.
An expression that has operands of different data types is called a mixed expression. A
mixed expression contains both integers and floating-point numbers.
In the first expression, the operand + has one integer operand and one floating-
point operand. In the second expression, both operands for the operator / are integers, the
first operand of + is the result of 6 / 4, and the second operand of + is a floatingpoint
number. The third example is an even more complicated mix of integers and floating-
point numbers. The obvious question is: How does C++ evaluate mixed expressions?
If the operator has the same types of operands (that is, either both integers or both
floating-point numbers), the operator is evaluated according to the type of operands.
Integer operands thus yield an integer result; floating-point numbers yield a floating-point
number. If the operator has both types of operands (that is, one is an integer and the other
is a floating-point number), then during calculation, the integer is changed to a floating-
point number with the decimal part of zero and the operator is evaluated. The result is a
floating-point number.
The entire expression is evaluated according to the precedence rules; the
multiplication, division, and modulus operators are evaluated before the addition and
subtraction operators. Operators having the same level of precedence are evaluated from
left to right. Grouping using parentheses is allowed for clarity. From these rules, it
follows that when evaluating a mixed expression, you concentrate on one operator at a
time, using the rules of precedence. If the operator to be evaluated has operands of the
same data type, evaluate the operator using Rule 1(a). That is, an operator with integer
operands will yield an integer result, and an operator with floating-point operands will
yield a floating-point result. If the operator to be evaluated has one integer operand and
one floating-point operand, before evaluating this operator, convert the integer operand to
a floating-point number with the decimal part of 0. The following examples show how to
evaluate mixed expressions.
D. Arithmetic Operators, Operator Precedence, and&Expressions
Arithmetic operators are fundamental symbols in programming languages used
for mathematical computations. They include addition, subtraction, multiplication,
division, and modulus. These operators enable programmers to perform various
mathematical operations, such as addition for combining values, subtraction for finding
differences, multiplication for repeated addition, division for distributing values, and
modulus for obtaining remainders.
Operator precedence dictates the order in which operators are evaluated within an
expression. It ensures that expressions are computed correctly by specifying which
operations take precedence over others. For example, multiplication and division
typically take precedence over addition and subtraction. Understanding operator
precedence is essential for writing clear and concise expressions, as it helps avoid
ambiguity and ensures the desired computation order.
Expressions in programming are the essence of computational logic,
encapsulating the fundamental operations that drive software functionality. Comprising
operands, which are the values or variables involved, and operators, which dictate the
actions to be performed, expressions span a wide spectrum of complexity, from
elementary arithmetic calculations to intricate logical evaluations.
At its core, expressions serve as the means through which programmers articulate
computational tasks and define the logic of their programs. By adeptly combining
arithmetic operators with variables, constants, and other elements, developers can craft
expressions that orchestrate a myriad of computational tasks with precision and
efficiency. Whether its performing basic arithmetic operations like addition, subtraction,
multiplication, and division, or executing advanced algorithms involving conditional
statements, loops, and function calls, expressions provide the mechanism for translating
conceptual logic into executable code.
Furthermore, expressions are not confined to arithmetic computations alone. They
extend their reach to encompass a diverse array of operations, including logical
comparisons, bitwise manipulations, and string concatenations, among others. This
versatility empowers programmers to tackle a broad spectrum of problem domains, from
numerical analysis and scientific computing to data processing, artificial intelligence, and
beyond.
Mastering expressions goes beyond mere competence; it is the cornerstone of
effective programming, shaping the very architecture and functionality of software
systems. With a deep understanding of expressions, developers unlock the full potential
of programming languages, empowering them to navigate complexities and innovate with
unparalleled creativity and problem-solving acumen.
Expressions serve as the bedrock upon which software systems are erected,
providing the framework for translating abstract concepts into executable code. They
embody the logic and algorithms that drive program behavior, encapsulating
computational tasks ranging from basic arithmetic calculations to intricate decision-
making processes and data manipulations. By honing their skills in crafting and
deciphering expressions, developers gain mastery over the intricate tapestry of
computational logic, enabling them to construct robust, scalable, and efficient software
solutions.
Proficiency in expressions equips developers with a versatile toolkit for tackling
diverse programming challenges. Armed with the ability to wield a multitude of
operators, functions, and data types, programmers can orchestrate complex operations
with precision and finesse. Whether its implementing sophisticated mathematical
algorithms, parsing intricate data structures, or orchestrating intricate control flows,
mastery of expressions empowers developers to navigate the complexities of software
development with confidence and agility.
Moreover, expressions serve as a conduit for creative expression and innovation
in programming. By harnessing the expressive power of programming languages,
developers can unleash their imagination and ingenuity, devising elegant solutions to
complex problems. Whether its devising novel algorithms, optimizing performance, or
designing intuitive user interfaces, the mastery of expressions empowers developers to
push the boundaries of whats possible in software development, ushering in a new era of
innovation and progress.
Furthermore, proficiency in expressions fosters collaboration and code
comprehension within development teams. Clear, well-structured expressions convey the
programmers intent effectively, facilitating communication and collaboration among
team members. Additionally, modularizing complex operations within concise
expressions promotes code reuse and maintainability, enhancing the scalability and
longevity of software projects.
In essence, mastering expressions is not just a technical skill; it is a foundational
pillar of effective programming. By cultivating expertise in crafting and deciphering
expressions, developers embark on a journey of exploration and discovery, uncovering
new possibilities and pushing the boundaries of whats achievable in software
development. As the digital landscape continues to evolve, the mastery of expressions
remains a timeless and indispensable asset for programmers seeking to make their mark
in the ever-changing world of technology.
Moreover, expressions play a crucial role in enhancing code readability,
maintainability, and scalability. Well-structured expressions convey the programmers
intent clearly, facilitating comprehension and collaboration among team members. They
also facilitate code reuse and modularization, as encapsulating complex operations within
concise expressions promotes code organization and abstraction.
In essence, expressions are the lifeblood of software development, breathing
functionality and intelligence into applications across diverse domains and industries.
From simple arithmetic calculations to sophisticated algorithmic manipulations,
expressions embody the essence of computational thinking, empowering programmers to
transform abstract concepts into tangible solutions that drive innovation and progress in
the digital realm. Thus, investing time and effort in mastering expressions is a wise
endeavor for any aspiring or seasoned programmer, as it lays the groundwork for success
and proficiency in the ever-evolving landscape of software engineering.
E. Type Conversion (Casting)
In the previous section, you learned that when evaluating an arithmetic
expression, if the operator has mixed operands, the integer value is changed to a floating-
point value with the zero decimal part. When a value of one data type is automatically
changed to another data type, an implicit type coercion is said to have occurred. As the
examples in the preceding section illustrate, if you are not careful about data types,
implicit type coercion can generate unexpected results. To avoid implicit type coercion,
C++ provides for explicit type conversion through the use of a cast operator.
The string data type in programming languages, including C++, is incredibly
versatile and far more intricate than simple primitive data types. Unlike basic data types
that merely store single values, strings offer a comprehensive suite of functionalities
tailored specifically for handling sequences of characters.
At its core, the string type not only allocates memory to accommodate the
characters comprising the string but also provides a plethora of built-in operations for
manipulating strings efficiently. These operations range from basic tasks like determining
the length of a string to more sophisticated functionalities such as substring extraction
and string comparison.
For instance, one fundamental operation supported by the string type is the ability
to ascertain the length of a string. This capability is indispensable for various string
processing tasks, enabling programmers to dynamically adjust their algorithms based on
the length of the input strings.
Moreover, the string data type facilitates operations for extracting substrings—
portions of a larger string—based on specified indices or patterns. This functionality is
invaluable in scenarios where specific segments of a string need to be isolated and
manipulated independently, such as parsing textual data or tokenizing input.
Furthermore, string types offer robust mechanisms for comparing strings,
enabling programmers to determine their equality or establish their relative order based
on lexicographical comparison. This feature is crucial for tasks like searching, sorting,
and filtering strings within a dataset, contributing to the efficiency and accuracy of string
processing algorithms.
As you progress through the upcoming chapters, youll delve deeper into the
intricacies of the string data type, exploring its myriad capabilities and learning how to
leverage them effectively in your programs. Topics will include advanced string
manipulation techniques, pattern matching algorithms, and strategies for optimizing
string processing performance.
Mastering the string data type and its associated operations opens up a vast array
of possibilities for programmers, providing them with the tools necessary to develop
highly sophisticated and versatile applications. With a deep understanding of strings,
programmers can leverage their capabilities to create software that is not only robust and
efficient but also feature-rich and user-friendly.
For instance, in the realm of text processing utilities, a comprehensive
understanding of string operations allows developers to implement powerful search and
manipulation functionalities. Whether its parsing complex textual data, performing
advanced pattern matching, or generating concise summaries from large documents,
mastery of strings enables programmers to build tools that streamline text-related tasks
with precision and ease.
Similarly, in the domain of data validation, strings play a pivotal role in ensuring
the integrity and accuracy of input data. By employing string manipulation techniques
such as regular expressions and custom validation routines, programmers can enforce
strict validation rules, safeguarding their applications against erroneous or malicious
input. This capability is particularly crucial in scenarios where data quality and
consistency are paramount, such as in financial transactions or medical records
management systems.
Furthermore, when it comes to designing user-friendly interfaces, strings serve as
the primary means of communication between the software and its users. A nuanced
understanding of string handling allows developers to craft interfaces that are intuitive,
informative, and responsive, enhancing the overall user experience. Whether it involves
presenting clear error messages, providing helpful tooltips, or localizing the applications
interface for diverse linguistic audiences, mastery of strings empowers programmers to
create interfaces that resonate with users on a deeper level.
Beyond these specific applications, the versatility of strings extends to virtually
every aspect of software development. From data serialization and communication
protocols to file handling and dynamic content generation, strings are ubiquitous in
modern computing environments. As such, a solid grasp of string manipulation
techniques is essential for tackling a wide range of programming challenges effectively
and efficiently.
In essence, by mastering the string data type and its associated operations,
programmers gain access to a powerful toolkit that can elevate their software projects to
new heights. Whether theyre developing cutting-edge algorithms, building intuitive user
interfaces, or ensuring data integrity and security, strings remain a cornerstone of modern
programming practice. As you continue to explore the intricacies of string manipulation
in your programming journey, youll discover endless possibilities for innovation and
creativity, transforming your ideas into reality with confidence and flair.
In summary, while simple data types provide basic storage facilities, the string
data type offers a sophisticated toolkit for handling textual data with precision and
efficiency. From basic operations like length calculation to advanced functionalities such
as substring extraction and string comparison, strings empower programmers to tackle a
wide range of string processing tasks with confidence and competence
F. Variables, Assignment Statements, and Input Statements
When you instruct the computer to allocate memory, you tell it not only what
names to use for each memory location, but also what type of data to store in those
memory locations. Knowing the location of data is essential, because data stored in one
memory location might be needed at several places in the program. As you saw earlier,
knowing what data type you have is crucial for performing accurate calculations. It is
also critical to know whether your data needs to remain fixed throughout program
execution or whether it should change.
Some data must stay the same throughout a program. For example, the conversion
formula that converts inches into centimeters is fixed, because 1 inch is always equal to
2.54 centimeters. When stored in memory, this type of data needs to be protected from
accidental changes during program execution. In C++, you can use a named constant to
instruct a program to mark those memory locations in which data is fixed throughout
program execution.
In an assignment statement, the value of the expression should match the data
type of the variable. The expression on the right side is evaluated, and its value is
assigned to the variable (and thus to a memory location) on the left side. A variable is
said to be initialized the first time a value is placed in the variable. Recall that in C++, =
is called the assignment operator.
Earlier, you learned that if a variable is used in an expression, the expression
would yield a meaningful value only if the variable has first been initialized. You also
learned that after declaring a variable, you can use an assignment statement to initialize it.
It is possible to initialize and declare variables at the same time. Before we discuss how
to use an input (read) statement, we address this important issue.
When a variable is declared, C++ may not automatically put a meaningful value
in it. In other words, C++ may not automatically initialize variables. For example, the int
and double variables may not be initialized to 0, as happens in some programming
languages. This does not mean, however, that there is no value in a variable after its
declaration. When a variable is declared, memory is allocated for it.
G. Increment and Decrement Operators
Because both the increment and decrement operators are built into C++, the value
of the variable is quickly incremented or decremented without having to use the form of
an assignment statement. Now, both the pre-and post-increment operators increment the
value of the variable by 1. Similarly, the pre- and post-decrement operators decrement the
value of the variable by 1. What is the difference between the pre and post forms of these
operators? The difference becomes apparent when the variable using these operators is
employed in an expression.
Suppose that x is an int variable. If ++x is used in an expression, first the value
ofGx is incremented by 1, and then the new value of x is used to evaluate the expression.
On the other hand, if x++ is used in an expression, first the current value of x is used in
the expression, and then the value of x is incremented by 1. The following example
clarifies the difference between the pre- and post-increment operators.
As before, the first statement assigns 5 to x. In the second statement, the
postincrement operator is applied to x. To execute the second statement, first the value of
x, which is 5, is used to evaluate the expression, and then the value of x is incremented to
6. Finally, the value of the expression, which is 5, is stored in y. After the second
statement executes, the value of x is 6, and the value of y is 5.
Obviously, you will use an output statement to produce this output. However, in
the programming code, this statement may not fit in one line as part of the output
statement. Note the semicolon at the end of the first statement and the identifier cout at
the beginning of the second statement. Also, note that there is no manipulator endl at the
end of the first statement. Here, two output statements are used to output the sentence in
one line. Recall that the newline character is n, which causes the insertion point to move
to the beginning of the next line. There are many escape sequences in C++, which allow
you to control the output. Table 2-4 lists some of the commonly used escape sequences.
H. Preprocessor Directives
Certain header files are provided as part of C++. Appendix F describes some of
the commonly used header files. Individual programmers can also create their own
header files, which is discussed in the chapter Classes and Data Abstraction, later in this
book. Note that the preprocessor commands are processed by the preprocessor before the
program goes through the compiler.
Earlier, you learned that both cin and cout are predefined identifiers. In ANSI/ISO
Standard C++, these identifiers are declared in the header file iostream, but within a
namespace. The name of this namespace is std. (The namespace mechanism will be
formally defined and discussed in detail in Chapter 7. For now, you need to know only
how to use cin and cout and, in fact, any other identifier from the header file iostream.)
There are several ways you can use an identifier declared in the namespace std.
One way to use cin and cout is to refer to them as std::cin and std::cout throughout the
program. The namespace mechanism is a feature of ANSI/ISO Standard C++. As you
learn more C++ programming, you will become aware of other header files. For example,
the header file cmath contains the specifications of many useful mathematical functions.
Similarly, the header file iomanip contains the specifications of many useful functions
and manipulators that help you format your output in a specific manner. However, just
like the identifiers in the header file iostream, the identifiers in ANSI/ ISO Standard C++
header files are declared within a namespace.
The name of the namespace in each of these header files is std. Therefore,
whenever certain features of a header file in ANSI/ISO Standard C++ are discussed, this
book will refer to the identifiers without the prefix std::. Moreover, to simplify the
accessing of identifiers in programs, the statement using namespace std; will be included.
Also, if a program uses multiple header files, only one using statement is needed. This
using statement typically appears after all the header files. Recall that the string data type
is a programmer-defined data type and is not directly available for use in a program. To
use the string data type, you need to access its definition from the header file string.
I. Creating a C++ Program
In previous sections, you learned enough C++ concepts to write meaningful
programs. You are now ready to create a complete C++ program. A C++ program is a
collection of functions, one of which is the function main. Therefore, if a C++ program
consists of only one function, then it must be the function main. Moreover, a function is a
set of instructions designed to accomplish a specific task. Until Chapter 6, you will deal
mainly with the function main. The statements to declare variables, the statements to
manipulate data (such as assignments), and the statements to input and output data are
placed within the function main. The statements to declare named constants are usually
placed outside of the function main.
A C++ program might use the resources provided by the IDE, such as the
necessary code to input the data, which would require your program to include certain
header files. You can, therefore, divide a C++ program into two parts: preprocessor
directives and the program. The preprocessor directives tell the compiler which header
files to include in the program. The program contains statements that accomplish
meaningful results. Taken together, the preprocessor directives and the program
statements constitute the C++ source code. Recall that to be useful, source code must be
saved in a file with the file extension .cpp. For example, if the source code is saved in the
file firstProgram, then the complete name of this file is firstProgram.cpp. The file
containing the source code is called the source code file or source file.
When the program is compiled, the compiler generates the object code, which is
saved in a file with the file extension .obj. When the object code is linked with the system
resources, the executable code is produced and saved in a file with the file extension .exe.
Typically, the name of the file containing the object code and the name of the file
containing the executable code are the same as the name of the file containing the source
code. For example, if the source code is located in a file named firstProg.cpp, the name of
the file containing the object code is firstProg.obj, and the name of the file containing the
executable code is firstProg.exe. The extensions as given in the preceding paragraph—
that is, .cpp, .obj, and .exe—are system dependent. Moreover, some IDEs maintain
programs in the form of projects. The name of the project and the name of the source file
need not be the same. It is possible that the name of the executable file is the name of the
project, with the extension .exe. To be certain, check your system or IDE documentation.
The preceding program works as follows: The statement in Line 1 includes the
header file iostream so that program can perform input/output. The statement in Line 2
uses the using namespace statement so that identifiers declared in the header file
iostream, such as cin, cout, and endl, can be used without using the prefix std::. The
statement in Line 3 declares the named constant NUMBER and sets its value to 12. The
statement in Line 4 contains the heading of the function main, and the left brace in Line 5
marks the beginning of the function main. The statements in Lines 6 and 7 declare the
variables firstNum and secondNum.
The statement in Line 8 sets the value of firstNum to 18 and the statement in
LineG9 outputs the value of firstNum. Next, the statement in Line 10 prompts the user to
enter an integer. The statement in Line 11 reads and stores the integer into the variable
secondNum, which is 15 in the sample run. The statement in Line 12 positions the cursor
on the screen at the beginning of the next line. The statement in Line 13 outputs the value
of secondNum.
J. Program Style and Form
In previous sections, you learned enough C++ concepts to write meaningful
programs. Before beginning to write programs, however, you need to learn their proper
structure, among other things. Using the proper structure for a C++ program makes it
easier to understand and subsequently modify the program. There is nothing more
frustrating than trying to follow and perhaps modify a program that is syntactically
correct but has no structure. In addition, every C++ program must satisfy certain rules of
the language. A C++ program must contain the function main. It must also follow the
syntax rules, which, like grammar rules, tell what is right and what is wrong and what is
legal and what is illegal in the language. Other rules serve the purpose of giving precise
meaning to the language; that is, they support the languages semantics.
The syntax rules of a language tell what is legal and what is not legal. Errors in
syntax are detected during compilation. When these statements are compiled, a
compilation error will occur at Line 2 because the semicolon is missing after the
declaration of the variable y. A second compilation error will occur at Line 4 because the
identifier w is used but has not been declared.
When the program is typed, errors are almost unavoidable. Therefore, when the
program is compiled, you are most likely to see syntax errors. It is quite possible that a
syntax error at a particular place might lead to syntax errors in several subsequent
statements. It is very common for the omission of a single character to cause four or five
error messages. However, when the first syntax error is removed and the program is
recompiled, subsequent syntax errors caused by this syntax error may disappear.
Therefore, you should correct syntax errors in the order in which the compiler lists them.
As you become more familiar and experienced with C++, you will learn how to quickly
spot and fix syntax errors. Also, compilers not only discover syntax errors, but also hint
and sometimes tell the user where the syntax errors are and how to fix them.
In C++, you use one or more blanks to separate numbers when data is input.
Blanks are also used to separate reserved words and identifiers from each other and from
other symbols. Blanks must never appear within a reserved word or identifier. All C++
statements must end with a semicolon. The semicolon is also called a statement
terminator. Note that curly braces, { and }, are not C++ statements in and of themselves,
even though they often appear on a line with no other code. You might regard brackets as
delimiters, because they enclose the body of a function and set it off from other parts of
the program.
The set of rules that gives meaning to a language is called semantics. For
example, the order-of-precedence rules for arithmetic operators are semantic rules. If a
program contains syntax errors, the compiler will warn you. What happens when a
program contains semantic errors? It is quite possible to eradicate all syntax errors in a
program and still not have it run. And if it runs, it may not do what you meant it to do.
The identifiers in the second set of statements, such as
CENTIMETERS_PER_INCH, are usually called self-documenting identifiers. As you
can see, self-documenting identifiers can make comments less necessary. Consider the
self-documenting identifier annualsale. This identifier is called a run-together word. In
using self-documenting identifiers, you may inadvertently include run-together words,
which may lessen the clarity of your documentation. You can make run-together words
easier to understand by either capitalizing the beginning of each new word or by inserting
an underscore just before a new word. For example, you could use either annualSale or
annual_sale to create an identifier that is more clear. Recall that earlier in this chapter, we
specified the general rules for naming named constants and variables. For example, an
identifier used to name a named constant is all uppercase. If this identifier is a run-
together word, then the words are separated with the underscore character, such as
CENTIMETERS_PER_INCH.
Part of good documentation is the use of clearly written prompts so that users will
know what to do when they interact with a program. There is nothing more frustrating
than sitting in front of a running program and not having the foggiest notion of whether to
enter something or what to enter. Prompt lines are executable statements that inform the
user what to do.
The programs that you write should be clear not only to you, but also to anyone
else. Therefore, you must properly document your programs. A well-documented
program is easier to understand and modify, even a long time after you originally wrote
it. You use comments to document programs. Comments should appear in a program to
explain the purpose of the program, identify who wrote it, and explain the purpose of
particular statements or groups of statements.
The computer would have no difficulty understanding either of these formats, but
the first form is easier to read and follow. Of course, the omission of a single comma or
semicolon in either format may lead to all sorts of strange error messages. The clarity of
the rules of syntax and semantics frees you to adopt formats that are pleasing to you and
easier to understand.
K. I/O Streams and Standard I/O Devices
You used cin and the extraction operator >> to get data from the keyboard, and
cout and the insertion operator << to send output to the screen. Because I/O operations
are fundamental to any programming language, in this chapter, you will learn about C++s
I/O operations in more detail. First, you will learn about statements that extract input
from the standard input device and send output to the standard output device. You will
then learn how to format output using manipulators. In addition, you will learn about the
limitations of the I/O operations associated with the standard I/O devices and learn how
to extend these operations to other devices.
A program performs three basic operations: It gets data, it manipulates the data,
and it outputs the results. In Chapter 2, you learned how to manipulate numeric data
using arithmetic operations. In later chapters, you will learn how to manipulate
nonnumeric data. Because writing programs for I/O is quite complex, C++ offers
extensive support for I/O operations by providing substantial prewritten I/O operations,
some of which you encountered in Chapter 2. In this chapter, you will learn about various
I/O operations that can greatly enhance the flexibility of your programs. In C++, I/O is a
sequence of bytes, called a stream, 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. Therefore, a stream is a sequence of characters from the
source to the destination.
Recall that the standard input device is usually the keyboard, and the standard
output device is usually the screen. To receive data from the keyboard and send output to
the screen, every C++ program must use the header file iostream. This header file
contains, among other things, the definitions of two data types, istream (input stream) and
ostream (output stream). The header file also contains two variable declarations, one for
cin (pronounced see-in), which stands for common input, and one for cout (pronounced
see-out), which stands for common output.
Now suppose that the input is 2. How does the extraction operator >> distinguish
between the character 2 and the number 2? The right-side operand of the extraction
operator >> makes this distinction. If the right-side operand is a variable of the data type
char, the input 2 is treated as the character 2 and, in this case, the ASCII value of 2 is
stored. If the right-side operand is a variable of the data type int or double, the input 2 is
treated as the number 2.
When reading data into a char variable, after skipping any leading whitespace
characters, the extraction operator >> 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 >> 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.
L. Using Predefined Functions in a Program
Recall from Chapter 2 that predefined functions are organized as a collection of
libraries, called header files. A particular header file may contain several functions.
Therefore, to use a particular function, you need to know the name of the function and a
few other things, which are described shortly. 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.
For example, to use the function pow, you must include the header file cmath.
The function pow has two parameters, which are decimal numbers. The function
calculates the first parameter to the power of the second parameter. (Appendix F
describes some commonly used header files and predefined functions.) The program in
the following example illustrates how to use predefined functions in a program. More
specifically, we use some math functions, from the header file cmath, and the string
function length, from the header file string. Note that the function length determines the
length of a string.
The preceding program works as follows. The statements in Lines 8 to 13 declare
the variables used in the program. The statement in Line 14 prompts the user to enter the
radius of the sphere, and the statement in Line 15 stores the radius in the variable
sphereRadius. The statement in Line 17 uses the function pow to compute and store the
volume of the sphere in the variable sphereVolume. The statement in Line 18 outputs the
volume. The statement in Line 19 prompts the user to enter the coordinates of two points
in the X-Y plane, and the statement in Line 20 stores the coordinates in the variables
point1X, point1Y, point2X, and point2Y, respectively. The statement in Line 22 uses the
functions sqrt and pow to determine the distance between the points. The statement in
Line 23 outputs the distance between the points. The statement in Line 24 stores the
string "Programming with C++" in str. The statement in Line 25 uses the string function
length to determine and output the length of str. Note how the function length is used.
Later in this chapter we will explain the meaning of expressions such as str.length().
Because I/O is fundamental to any programming language and because writing
instructions to perform a specific I/O operation is not a job for everyone, every
programming language provides a set of useful functions to perform specific I/O
operations. In the remainder of this chapter, you will learn how to use some of these
functions in a program. As a programmer, you must pay close attention to how these
functions are used so that you can get the most out of them. The first function you will
learn about here is the function get.
When the computer executes this statement, A is stored in ch1, the blank is
skipped by the extraction operator >>, the character 2 is stored in ch2, and 5 is stored in
num. However, what if you intended to store A in ch1, the blank in ch2, and 25 in num?
It is clear that you cannot use the extraction operator >> to input this data. As stated
earlier, sometimes you need to process the entire input, including whitespace characters,
such as blanks and the newline character. For example, suppose you want to process the
entered data on a line-by-line basis. Because the extraction operator >> skips the newline
character and unless the program captures the newline character, the computer does not
know where one line ends and the next begins.
Here, intExp is an integer expression yielding an integer value, and chExp is a
char expression yielding a char value. In fact, the value of the expression intExp specifies
the maximum number of characters to be ignored in a line. Suppose intExp yields a value
of, say 100. This statement says to ignore the next 100 characters or ignore the input until
it encounters the character specified by chExp, whichever comes first.
When this statement executes, it ignores either the next 100 characters or all
characters until the newline character is found, whichever comes first. For example, if the
next 120 characters do not contain the newline character, then only the first 100
characters are discarded and the next input data is the character 101. However, if the 75th
character is the newline character, then the first 75 characters are discarded and the next
input data is the 76th character.
Suppose you are processing data that is a mixture of numbers and characters.
Moreover, the numbers must be read and processed as numbers. You have also looked at
many sets of sample data and cannot determine whether the next input is a character or a
number. You could read the entire data set character by character and check whether a
certain character is a digit. If a digit is found, you could then read the remaining digits of
the number and somehow convert these characters into numbers. This programming code
would be somewhat complex. Fortunately, C++ provides two very useful stream
functions that can be used effectively in these types of situations.
The stream function putback lets you put the last character extracted from the
input stream by the get function back into the input stream. The stream function peek
looks into the input stream and tells you what the next character is without removing it
from the input stream. By using these functions, after determining that the next input is a
number, you can read it as a number. You do not have to read the digits of the number as
characters and then convert these characters to that number.
The peek function returns the next character from the input stream but does not
remove the character from that stream. In other words, the function peek looks into the
input stream and checks the identity of the next input character. Moreover, after checking
the next input character in the input stream, it can store this character in a designated
memory location without removing it from the input stream. That is, when you use the
peek function, the next input character stays the same, even though you now know what
it is.
What actually happens when the input stream enters the fail state? Once an input
stream enters the 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 produces incorrect results. In this sample run, the third input is q56 and
the cin statement tries to input this into the variable weight. However, the input q56
begins with the character q and weight is a variable of type int, so cin enters the fail state.
Note that the printed values of the variables weight and height are unchanged, as shown
by the output of the statements in Lines 15 and 16.
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. After using the function clear to return the input stream to a working state,
you still need to clear the rest of the garbage from the input stream. This can be
accomplished by using the function ignore.
M. Output and Formatting Output
Other than writing efficient programs, generating the desired output is one of a
programmers highest priorities. Chapter 2 briefly introduced the process involved in
generating output on the standard output device. More precisely, you learned how to use
the insertion operator << and the manipulator endl to display results on the standard
output device.
However, there is a lot more to output than just displaying results. Sometimes,
floatingpoint numbers must be output in a specific way. For example, a paycheck must be
printed to two decimal places, whereas the results of a scientific experiment might require
the output of floating-point numbers to six, seven, or perhaps even ten decimal places.
Also, you might like to align the numbers in specific columns or fill the empty space
between strings and numbers with a character other than the blank. For example, in
preparing the table of contents, the space between the section heading and the page
number might need to be filled with dots or dashes. In this section, you will learn about
various output functions and manipulators that allow you to format your output in a
desired way.
You use the manipulator setprecision to control the output of floating-point
numbers. Usually, the default output of floating-point numbers is scientific notation.
Some integrated development environments (IDEs) might use a maximum of six decimal
places for the default output of floating-point numbers. However, when an employees
paycheck is printed, the desired output is a maximum of two decimal places. To print
floating-point output to two decimal places, you use the setprecision manipulator to set
the precision to 2.
The sample run shows that when the value of rate and tolerance are printed
without setting the scientific or fixed manipulators, the trailing zeros are not shown and,
in the case of rate, the decimal point is also not shown. After setting the manipulators, the
values are printed to six decimal places. In the next section, we describe the manipulator
showpoint to force the system to show the decimal point and trailing zeros. We will then
give an example to show how to use the manipulators setprecision, fixed, and showpoint
to get the desired output.
Suppose that the decimal part of a decimal number is zero. In this case, 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. Reading and writing
of long numbers can be error prone. For example, suppose you are dealing with the
number 87523872918. Typically, this number is written as 87,523,872,918. However, in
C++, commas cannot be used to separate the digits of a number. To make the reading and
writing of long numbers easier C++ 14 introduces digit separator (single-quote
character). So in C++ 14, the number 87523872918 can be represented as 87523872918.
The program in the following example further illustrates this.
The manipulator setw is used to output the value of an expression in a specific
number of columns. The value of the expression can be either a string or a number. The
expression setw(n) outputs the value of the next expression in n columns. The output is
right-justified. Thus, if you specify the number of columns to be 8, for example, and the
output requires only four columns, the first four columns are left blank. Furthermore, if
the number of columns specified is less than the number of columns required by the
output, the output automatically expands to the required number of columns; the output is
not truncated.
The statement in Line 17 sets the output of miles in two columns. However, the
value of miles contains three digits, so the value of miles is expanded to the right number
of columns. After printing the value of miles, the value of the string "error" is printed in
the next seven columns followed by the value of error. Because to output the value of
error the number of columns is not specified, after printing the string "error" the value of
error is printed (see the last line of the output).
In the previous section, you learned how to use the manipulators setprecision,
fixed, and showpoint to control the output of floating-point numbers and how to use the
manipulator setw to display the output in specific columns. Even though these
manipulators are adequate to produce an elegant report, in some situations, you may want
to do more. In this section, you will learn additional formatting tools that give you more
control over your output.
Recall that in the manipulator setw, if the number of columns specified exceeds
the number of columns required by the expression, the output of the expression is
rightjustified and the unused columns to the left are filled with spaces. The output stream
variables can use the manipulator setfill to fill the unused columns with a character other
than a space. The output of the statement in Line 15—the fourth line of output—is similar
to the output of the statement in Line 14, except that the filling character for gpa and
scholarship is #. In the output of the statement in Line 16 (the fifth line of output), the
filling character for name is @, the filling character for gpa is #, and the filling character
for scholarship is ^. The manipulator setfill sets these filling characters.
Recall that if the number of columns specified in the setw manipulator exceeds
the number of columns required by the next expression, the default output is
rightjustified. Sometimes, you might want the output to be left-justified. To left-justify
the output, you use the manipulator left.
N. File Input/Output
The previous sections discussed in some detail how to literally particularly get
input from the keyboard (standard input device) and basically really send output to the
screen (standard output device), or so they kind of thought, which literally is fairly
significant. However, getting input from the keyboard and sending output to the screen
essentially have for all intents and purposes for all intents and purposes several
limitations, which for the most part is fairly significant in a subtle way. Inputting data in a
program from the keyboard really is fairly comfortable as generally long as the amount of
input generally is very small in a subtle way, or so they generally thought. Sending output
to the screen works well if the amount of data generally definitely is small (no kind of
fairly larger than the size of the screen) and you essentially do not definitely specifically
want to for the most part distribute the output in a printed format to others, really
basically contrary to popular belief, which specifically is fairly significant.
When confronted with a substantial volume of input data, relying solely on pretty
fairly manual keyboard input becomes impractical and error-prone in a very major way.
Not only really is it cumbersome to input fairly really large datasets manually, but the for
all intents and purposes basically potential for errors sort of for all intents and purposes
due to typos or inadvertent mistakes increases significantly, for all intents and purposes
basically contrary to popular belief. To mitigate these challenges and streamline the input
process, programmers need alternative methods for supplying data to their programs. One
approach to address this issue essentially is through the utilization of external data
sources, fairly for all intents and purposes contrary to popular belief in a subtle way. By
leveraging external sources, basically very such as files, databases, or network
connections, programmers can pre-process the required data before executing their
programs. This pre-processing step allows for the data to actually really be organized,
validated, and sanitized, reducing the likelihood of errors and ensuring the integrity of the
input, or so they essentially thought. For instance, data stored in a file can for the most
part mostly be formatted and validated prior to program execution, eliminating the need
for actually manual input and minimizing the risk of errors, which generally kind of is
quite significant, contrary to popular belief. Similarly, data retrieved from a database can
definitely undergo preprocessing steps, sort of kind of such as filtering or aggregation, to
particularly for the most part ensure its suitability for the programs requirements, which
definitely for all intents and purposes is quite significant in a subtle way.
By decoupling the input data from the program execution, developers can for all
intents and purposes generally achieve for all intents and purposes kind of greater
flexibility and reliability in their applications, or so they mostly particularly thought.
Moreover, by adopting alternative data sources, programs gain the ability to access the
same dataset consistently across actually really multiple executions, which for the most
part actually is fairly significant in a sort of major way. This consistency ensures
reproducibility and reliability in the programs behavior, as it operates on a predefined
dataset rather than relying on potentially particularly kind of variable for all intents and
purposes actually manual inputs, for all intents and purposes for all intents and purposes
contrary to popular belief, which is fairly significant. In the context of for the most part
file input/output operations in C++, the fstream header generally basically file kind of
basically plays a pivotal role in facilitating interactions with external data sources in a for
all intents and purposes major way.
Through ifstream and ofstream, programmers can particularly basically read from
and basically write to files seamlessly, enabling efficient data exchange between the
program and external files in a subtle way, which is quite significant. This capability not
only enhances the programs usability but also promotes code modularity and reusability
by decoupling the data processing logic from the input mechanism, which generally kind
of is fairly significant in a really major way. In summary, while definitely for all intents
and purposes manual keyboard input may really for the most part suffice for small
datasets, it becomes impractical and error-prone for kind of much larger volumes of data
in a subtle way, showing how the previous sections discussed in some detail how to
literally actually get input from the keyboard (standard input device) and basically
essentially send output to the screen (standard output device), or so they kind of really
thought in a subtle way. By embracing alternative data sources and leveraging literally
for all intents and purposes file I/O operations provided by the fstream header for the
most part for the most part file in C++, programmers can streamline the input process, for
the most part literally enhance the reliability of their programs, and actually generally
promote code maintainability and scalability, which for all intents and purposes definitely
is fairly significant, actually contrary to popular belief.
Suppose you for all intents and purposes generally want to sort of really present
the output of a program in a meeting, definitely basically further showing how in the
context of for all intents and purposes specifically file input/output operations in C++, the
fstream header specifically mostly file for all intents and purposes kind of plays a pivotal
role in facilitating interactions with external data sources, which basically is fairly
significant. Distributing printed copies of the program output specifically definitely is a
sort of generally better approach than showing the output on a screen in a kind of
particularly big way, which really is quite significant. For example, you might actually
generally give a printed report to each member of a committee before an important
meeting, or so they particularly essentially thought in a subtle way. Furthermore, output
must sometimes for all intents and purposes for all intents and purposes be saved so that
the output produced by one program can literally essentially be used as an input to
generally kind of other programs. The integration of the fstream header particularly file
into C++ programs significantly extends their capabilities beyond actually for all intents
and purposes standard input and output operations in a kind of particularly major way.
While iostream manages interactions with the definitely standard input and output
devices, fstream introduces functionalities tailored for mostly generally file input and
output tasks, allowing programmers to particularly literally manipulate files directly on
the filesystem in a subtle way, which for the most part is fairly significant.
Within the fstream header file, two really for all intents and purposes key data
types particularly mostly are defined: ifstream and ofstream, which basically is quite
significant. These data types basically literally serve as interfaces for mostly for the most
part file input and output operations, respectively, paralleling the functionality of istream
and ostream for all intents and purposes standard input and output in a subtle way, so
furthermore, output must sometimes for all intents and purposes mostly be saved so that
the output produced by one program can literally mostly be used as an input to generally
fairly other programs. The integration of the fstream header particularly literally file into
C++ programs significantly extends their capabilities beyond actually standard input and
output operations in a kind of major way in a subtle way. Understanding these data types
and their functionalities really particularly is crucial for effectively working with files in
C++, sort of fairly contrary to popular belief, or so they for the most part thought. The
ifstream (Input kind of literally File Stream), this data type enables C++ programs to
particularly for all intents and purposes read data from files, which kind of shows that
distributing printed copies of the program output for all intents and purposes definitely is
a sort of sort of better approach than showing the output on a screen, which literally
generally is fairly significant, so in summary, while definitely pretty manual keyboard
input may really mostly suffice for small datasets, it becomes impractical and error-prone
for kind of generally larger volumes of data in a subtle way, showing how the previous
sections discussed in some detail how to literally get input from the keyboard (standard
input device) and basically particularly send output to the screen (standard output
device), or so they kind of thought, or so they generally thought.
Similar to istream, ifstream provides methods for extracting data from a file,
facilitating tasks for all intents and purposes definitely such as parsing configuration files,
analyzing datasets, or reading serialized objects, which essentially is fairly significant in a
sort of big way. The ofstream (Output for the most part essentially File Stream),
conversely, ofstream facilitates writing data to files within C++ programs. Similar to
ostream, ofstream empowers programmers to output data to files, enabling applications to
store information persistently for future use or share data with kind of other programs. By
leveraging ifstream and ofstream, alongside the broader capabilities of the fstream header
file, C++ programmers can really develop robust applications capable of handling a
diverse array of file-related tasks in a generally for all intents and purposes major way in
a kind of major way.
Whether building text processing utilities, database systems, or definitely sort of
other applications, mastering particularly literally file I/O operations basically essentially
is particularly essential for unlocking the generally for all intents and purposes full very
definitely potential of C++ programs. In summary, while iostream forms the foundation
for generally standard input and output operations in C++, the fstream header mostly kind
of file extends these capabilities to essentially literally file I/O, introducing ifstream and
ofstream for reading from and writing to files, respectively in a very generally big way,
which mostly is quite significant. Understanding and utilizing these functionalities for the
most part is definitely generally essential for building versatile and efficient C++
applications that basically definitely interact with external data sources, demonstrating
that for example, you might for all intents and purposes kind of give a printed report to
each member of a committee before an important meeting, fairly basically contrary to
popular belief.
Students also viewed