The values and expressions used in C++ are displayed using
the cout extractor. To make the displaying of data more realistic, the
cout is configured to handle or format data to any desired result. While the
cout (as a class) is defined in the iostream file, some other files provide
other extensive techniques for displaying data to the console. The C language
also is equipped with other formatting functions used for the same purpose. The
ability to create a program made of mixed C and C++ language enhances these
formatting possibilities.
General Display Techniques
With cout
|
|
The ostream class (although we have not learned about classes yet, we
can explore them without knowing what a class is) has allowed us so far to
display items on the console screen. It is from the ios library and
commands all techniques of data output to C++ console applications. The cout
we have used so far is a “child” of the ostream library. Using it, we
have found out that we can display almost any type of value. For example, it can
be used to display:
- A word or sentence, called a string:
cout << "Major = South African History";
- A character:
cout << 'G';
- A short integer:
cout << -10540;
- An integer:
cout << 242;
- A long integer:
cout << 46300540;
- A floating number:
cout << 126.50;
- Or a double-precision number:
cout << 440005.55;
Instead of displaying a value just using the cout
extractor, you can first declare and initialize a variable before displaying its
value.
Like the ostream, the cout is also referred to
as an object. Besides the cout and the extraction operator << used
to display a character, the cout can be used to display a (one)
character. To do this, type cout followed by a period and followed by the
put() member function. The syntaxes of the put() function are:
ostream& put(char);
ostream& put(unsigned char);
ostream& put(signed char);
|
The character must be included between parentheses and
single-quotes. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
cout.put('P');
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
If the character is initialized from a variable, type the name of the
variable between parentheses:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
char Category = 'T';
cout.put(Category);
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
The character can also come from a variable requested from the user.
The cout.write() Function
|
|
If you want to display a whole string, use the write()
function. This function requires two arguments. First, you must specify the
string that is used as the source. Second, the compiler needs to know how many
characters from the source will be displayed (or considered). Here are two
examples:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
char Peripheral[] = "Digital Camera";
// First example of using the write() member function of the cout class
cout.write("The 5th Floor", 13);
cout << endl;
// Second example of using the write() function
cout.write(Peripheral, 8);
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
Although the second argument is used to display a fixed
number of characters, if you want to display the whole string, you must make
sure the value of the second argument is greater than or equal to the length of
the source string. Instead of visually counting the number of characters, which
could lead to a mistake, you can use the sizeof operator to get the
length of the string:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
char Peripheral[] = "Digital Camera";
int Count = sizeof(Peripheral) / sizeof(char);
cout.write(Peripheral, Count);
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
Data Display Functions: puts()
|
|
The C++ (Builder) compiler ships with other files that
provide many other functions that can be used to control how data displays on
the screen. One of these files is the stdio.h header.
The puts() function is used to display a string on
the console. Its syntaxes are:
int puts(const char *Str);
The Str argument must be a regular string enclosed in double-quotes.
Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
char Answer;
puts("Do you consider yourself a hot-tempered individual? ");
cin >> Answer;
cout << "\nYour answer was: " << Answer;
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
The puts() function lacks the formatting
possibilities of cout. It is destined to only display a single string. To
display more complex strings, you can combine it with other operators or
functions. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
char Answer;
puts("Do you consider yourself a hot-tempered individual? ");
cin >> Answer;
puts("\nYour answer was: ");
cout.put(Answer);
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
The string to display on a puts() function can also
originate from a declared and initialized variable. In this case, you would
provide the name of the variable as the argument to the function. Here is an
example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
char Question[] = "Do you consider yourself a hot-tempered individual? ";
char Answer;
puts(Question);
cin >> Answer;
puts("\nYour answer was: ");
cout.put(Answer);
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
The puts() function positions the cursor of the
subsequent line. If you find this annoying, you can use the cputs()
function. The cputs() function is used to display a string on the
console. Its syntax is:
int cputs(const char *Str);
To display a string using the cputs() function, pass
a string as the argument. The cputs() function requires the conio
header file. Here are two examples:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
char Answer;
cputs("Do you consider yourself a hot-tempered individual? ");
cin >> Answer;
cputs("\nYour answer was: ");
cout.put(Answer);
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
If the string is from a variable, provide the name of the variable as
argument.
The printf() function is mostly used in the C language
programs. By default, it is used to display a string on the console. Its simpler
syntax is:
int printf(const string);
To display a string using the printf() function, simply enclose it
between double-quotes, as the function’s argument. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
printf("Welcome to College Park Auto-Parts");
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
While the printf() is a function of the stdio.h file, the conio.h
library provides an alternative to display a string on the console. The function
used is cprintf() and its basic syntax is:
int cprintf(const string);
This function behaves the same way as the stdio.h’s printf()
function.
Controlling and Formatting Data Output
|
|
The Width of Data Display
|
|
The width() function is used to set the amount of
space needed to display an item on the console. Its syntax is:
int width();
int width(int Count);
The first version of this function displays the intended
value “as is”. The second version takes one integer as argument, Count. In
order to display the intended value that could be an array of characters, an
integer or a floating number, the compiler would count the number of characters
(for a char or a string) or the number of digits (for an integer or a float,
including the period for decimals). If the value of the argument you supplied,
Count, is less than or equal to the number of characters or digits, the compiler
would ignore your argument, Count, and display the intended value. If the value
argument is greater than the number of characters or digits, the compiler would
display the intended value using the total value of the argument, Count, but
leaving empty spaces on the left of the intended value.
The value to display comes after calling the width()
function. If you are displaying only one value, the scenario above would apply
straight forward. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
int Value = 782;
cout.width(6);
cout << Value;
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
To display various values, you can call the width() function for each
and they can use different width values as in the following example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
double Value1 = 6.5, Value2 = 25.56, Value3 = 28478.12;
cout.width(8);
cout << Value1 << endl;
cout.width(14);
cout << Value2 << endl;
cout.width(10);
cout << Value3 << endl;
cout << "\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
An alternative to using the width() function is to call the setw()
function:
int setw(int w);
This function takes an integer argument that specifies the amount of space
used to display the intended value. Like the width() function, the setw()
function can be used to format one value at a time. Here is an example of using
it:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
double Value1 = 6.5, Value2 = 25.56, Value3 = 28478.12;
cout.width(16);
cout << Value1 << endl;
cout << setw(8) << Value2 << endl;
cout << setw(12) << Value3 << endl;
cout << "\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
As we have seen already, the compiler leaves empty spaces on the left side of
the displaying value if the width is greater than the needed space. If you do
not want that space to be empty, you can fill it with any character you want. To
do that, call the fill() function:
char fill();
char fill(char c);
The second fill() function takes one argument as the character that
would be used in place of the empty spaces. The argument is a character that can
be included between single-quotes. If no fill() function was called
previously, the second version displays the intended value “as is”. If there
was a previous call to the fill(char c) version that takes a character
argument, the first version, fill(), immediately following would still keep the
argument of the previous call to fill(), then empty it. In other words, if there
is another call to the fill() version without argument, no character
would be displayed, until a new call to the fill(char c) function. Here
is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
double Value1 = 6.5, Value2 = 25.56, Value3 = 28478.12, Value4 = 10.05;
cout.width(12);
cout << Value1 << endl;
cout.width(12);
cout.fill('#');
cout << Value2 << endl;
cout.width(12);
cout.fill();
cout << Value3 << endl;
cout.fill();
cout << Value4 << endl;
cout << "\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
Like the fill() function, the iomanip library provides the setfill()
function to fill out empty spaces on a line formatted with the setw()
function. The syntax of the setfill() function is:
This function takes one character as argument. This character would be used
to fill out the empty spaces on the left of a value displayed on a subsequent
cout. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
double Value1 = 6.5, Value2 = 28478.12, Value3 = 35.25;
string WebSite = ".functionx.com";
cout << setw(16) << setfill('%');
cout << Value1 << endl;
cout << setw(8) << setfill('@') << Value2 << endl;
cout << setw(12) << Value3 << endl;
cout << setw(17) << setfill('w') << WebSite << endl;
cout << "\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
The dec, hex, and oct Operators
|
|
The most usual way to show an integer number on the console is to display it
“as is”. To display a variable that has been declared and initialized as
int Value = 152;
you would write:
cout << Value;
The compiler would take care of displaying it. If you have an integer in
decimal format and would like to display its equivalent hexadecimal
representation, use the hex operator as follows:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
int Value = 242;
cout << "Value = " << Value << endl;
cout << "Value = " << hex << Value << endl;
cout << "\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
If you have a hexadecimal integer and would like to display it in a decimal
format, simply use the cout operator followed by the value. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
cout << "Number = " << 0xFE28D;
cout << "\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
Although all integers are displayed in decimal format by default, you can
explicitly ask the compiler to reinforce that notation. You can also display the
same value in either format as follows:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
int Variable = 28045;
cout << "Declared Variable: " << Variable << endl;
cout << "In decimal: " << dec << Variable << endl;
cout << "In hexadecimal: " << hex << Variable << endl;
cout << "\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
This would produce:
Declared Variable: 28045
In decimal: 28045
In hexadecimal: 6d8d
Press any key to continue...
|
Although the hex and dec words are used as operators, they are
indeed functions that each takes one argument. Such an argument is passed by
reference, which means the argument retains the new value after being operated
on. For example, if you pass a decimal integer to the hex function, the
argument will be maintained as hexadecimal. That is what happens with the
following example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
int Variable = 28045;
cout << "Declared Variable: " << Variable << endl;
cout << "In decimal: " << dec << Variable << endl;
cout << "In hexadecimal: " << hex << Variable << endl;
cout << "Declared Variable: " << Variable << endl;
cout << "\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
This would produce:
Declared Variable: 28045
In decimal: 28045
In hexadecimal: 6d8d
Declared Variable: 6d8d
Press any key to continue...
|
As you have found out, the hex attribute is used to display the
hexadecimal equivalent of a decimal number, but such a number displays in
lowercase. To display the hexadecimal letters to uppercase, include the
uppercase attribute. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
int SayIt = 12;
cout << hex << uppercase << SayIt << endl;
cout << "\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
The uppercase attribute can precede or succeed the hex attribute, as
illustrated by the following example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
long Value = 3874238;
cout << uppercase << hex << Value << endl;
cout << "\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
The setiosflags() Function
|
|
The width() member function and the setw() functions are
typically used to right-align the value(s) displayed that otherwise would be
left aligned. If you want to explicitly left align a value, use the setioflags()
function. This function takes only one argument as the type of flags used to
display data. In order to use the setiosflags() function, you must
qualify its flags using the library in which the flag is defined.
The ios::left flag is used to left-align a value.
Here is a simple example that displays an integer:
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
int Series = 2014;
cout << setiosflags(ios::left) << Series;
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
The resetiosflags()
Function
|
|
After calling the setiosflags() function, any value displayed would
follow the rule of that function. To remove the formatting set by the setiosflags(),
use the resetiosflags() function, usually with the same argument:
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
int Series = 2014;
double Price = 12.95;
cout << setiosflags(ios::left) << Series << endl;
cout << resetiosflags(ios::left) << setw(8) << Price;
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
Formatting Floating-Point Numbers
|
|
In most programs that use precise numbers, you need to be able to format your
values to display appropriately. This is made possible with the use of the setprecision()
function:
int setprecision(int p);
This function takes one argument as the number of decimal places displayed
after the period of the floating number. In order to effectively use the setprecision()
funciton, first call the setiosflags() function with the appropriate
flag. The ios::fixed flag allows you to specify
the exact number of decimal values used in the setprecision() function.
Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
double Price = 0.5;
cout << setiosflags(ios::fixed) << setprecision(2) << Price << endl;
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
Since the setiosflags() and the setprecision() functions apply
their formatting to all values set after they have been called, you can use them
once and format your other values. That is, until you call these functions
again. This is used in the following example:
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
int Qty1 = 2, Qty2 = 5,
Qty3 = 4, Qty4 = 1;
double Price1 = 0.5, Price2 = 1.25,
Price3 = 2.95, Price4 = 1.65;
double Total1 = Qty1 * Price2,
Total2 = Qty4 * Price3,
Total3 = Qty2 * Price1,
Total4 = Qty3 * Price4;
cout << setiosflags(ios::fixed) << setprecision(2);
cout << "Total 1 = " << Total1 << endl;
cout << "Total 2 = " << Total2 << endl;
cout << "Total 3 = " << Total3 << endl;
cout << "Total 4 = " << Total4 << endl;
cout << "\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
You can also display floating numbers using a
scientific format. To do that, set the flag of the setiosflags() function
to ios::scientific. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
double Pop = 25.44059,
Distance = 212.625,
MaxExp = 709.78222656;
cout << setiosflags(ios::scientific) << setprecision(2);
cout << "PI = " << Pop << endl;
cout << "Distance = " << Distance << endl;
cout << "Exponent = " << MaxExp << endl;
cout << "\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
This would produce:
PI = 2.54e+01
Distance = 2.13e+02
Exponent = 7.10e+02
Press any key to continue...
|
The C language is the parent of C++. As such, C++ inherits what is available
from its parent C. This flexibility also allows you to mix the way things are
done in C and the features that are available in C++. Although C is C++’
parent, you do not need to know (anything) about C in order to program in C++
(in fact, you should not know anything about C, at all). Nevertheless, we will
review these features transparently and we will be concerned only with the
reason we are here: how to program in C++.
To format the display of data in C++, the cout operator (once again,
it is a class) is complete. In some circumstances, and this will become common
when writing applications using some of Borland classes (such as AnsiString),
you will need to know how other objects format data. The most common function
used to display data in C, and some legacy C++ code, is the printf()
function. As flexible as it is, it does not use the type of syntax we are
already getting used to in C++.
From a C++ stand point, to display data using the functions, everything
depends on how you want data to appear. Data types are divided in categories:
characters, integers, floating-point numbers, and strings. To display a
particular type, you type the percent operator “%”, followed by the category
of data. An example would be “%d”.
To display a character, use the %c format to represent a character variable.
Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
char Gender = 'M';
printf("Member Gender: %c", Gender);
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
To display an integer, use the %operator with one of the following tags:
Tag |
Integer
Type to Display |
d |
signed decimal integer |
i |
signed decimal integer |
o |
unsigned octal integer |
u |
unsigned decimal integer |
x |
unsigned hexadecimal int (with a, b, c, d, e, f) |
X |
unsigned hexadecimal int (with A, B, C, D, E, F) |
|
Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
int Number = 120;
printf("Number: %d", Number);
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
To display a floating-point number, use the % operator with one of the
following formats:
Tag |
To
display |
f |
signed value of the form [-]dddd.dddd |
e |
signed value of the form [-]d.dddd or e[+/-]ddd |
g |
signed value in either e or f form, based on given
value and precision.
Trailing zeros and the decimal point are printed if necessary. |
E |
Same as e; with E for exponent |
G |
Same as g; with E for exponent if e format used |
|
Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
double Distance = 272.44;
printf("Distance: %f", Distance);
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
To set the number of decimal places after the period, type the % operator,
followed by a period, followed by an integer for the number of decimal places
desired, followed by the desired tag. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
double Floater = 3255.01265;
printf("Floater: %.3f", Floater);
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
To display a string, use the %s format. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
char FIFA[] = "Federation Internationale de Football Association";
printf("World Cup Supervisor: %s", FIFA);
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
Data input in C++ is performed using the cin operator (cin also is a
class). The cin is configured with so much flexibility (in C++, we consider that
it is overloaded; in reality, it is the >> operator that is overloaded)
that it can retrieve any type of declared regular variable. This includes
integers, characters, floating-point numbers, or arrays of characters. Here are
examples of variables that the cin can handle:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
cout << "Enter a natural number: ";
int Natural;
// Retrieve an integer
cin >> Natural;
cout << "Type a decimal number: ";
float Floater;
// Requesting a floating pointing number
cin >> Floater;
cout << "Type another decimal number: ";
double Precision;
// Retrieving a double-precision number
cin >> Precision;
cout << "Are you ready for C++ (y=Yes/n=No)? ";
char Answer;
// Requesting a character
cin >> Answer;
cout << "I mean, are you really ready (Type Yes or No)? ";
char Explicit[10];
// Retrieving a word
cin >> Explicit;
cout << "\nHere is what we got from you";
cout << "\nNatural Number: " << Natural;
cout << "\nFloating Number: " << Floater;
cout << "\nDouble Precision: " << Precision;
if( Answer == 'y' || Answer == 'Y' )
cout << "\nYou are ready for C++";
else
cout << "\nYou are still not committed to C++";
cout << "\nYour readiness for C++: " << Explicit;
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
The gets() function, as its name implies, is used to retrieve a string
from the user. This function can receive a string of almost any length,
depending on how you declare the string.
To use the gets() function to request a string, include the stdio.h
header file to your source. After declaring the string variable, provide it as
argument to the gets() function. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
char Answer[80];
puts("Are you ready to rumbleeeeee? ");
gets(Answer);
cout << "\nThe audience response: " << Answer;
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
Here is an example of running the program:
Are you ready to rumbleeeeee?
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
The audience response: yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
Press any key to continue...
|
To request data from the user, or to retrieve it somehow, you can use the scanf()
function that is part of the stdio.h file. To use this function, you must
provide two pieces of information. First the function needs to know the type of
variable the function is expecting. Each data type is represented by a letter as
follows:
Character |
Used
for |
c |
A single character |
d |
An integer |
e |
A floating-point number |
f |
A floating-point number |
g |
A floating-point number |
h |
A short integer |
i |
A decimal, a hexadecimal, or an octal integer |
o |
An octal integer |
s |
A string followed by a white space character |
u |
An unsigned decimal integer |
x |
A hexadecimal integer |
|
When calling the scanf() function to retrieve a specific value, the
appropriate character must be preceded by an ampersand “%” and both must be
included in double-quotes. For example, to request an integer, you would write
“%d”. The second piece of information the function needs is the name of the
declared variable. Because you are planning to change the value of the variable,
it must be passed by reference. To use the scanf() function, you can include it
in a C program. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
float Number;
printf("Type a number: ");
scanf("%f", &Number);
printf("\nYou typed: %f\n", Number);
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
Here is an example of running the program:
Type a number: 145.50
You typed: 145.500000
Press any key to continue...
|
You can also mix C functions, such as printf() or scanf() in your C++ program
as you see fit. For example, you can retrieve values using either cin or scanf()
to retrieve any value. In the same way, you can use scanf(), cin,
or gets() when requesting a string. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
char FullName[32];
char Gender;
int Books;
cout << "Type your full name: ";
gets(FullName);
cout << "Type your gender (m=Male/f=Female): ";
cin >> Gender;
cout << "How many books do you own? ";
scanf("%d", &Books);
cout << "\nWell, " << FullName << ", with " << Books
<< " books, it looks like you read a lot! ";
if( Gender == 'm' || Gender == 'M' )
puts("You are the man");
else
puts("You go, girl");
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
Here is an example of running the program:
Type your full name: Jacob Desvarieux
Type your gender (m=Male/f=Female): m
How many books do you own? 84
Well, Jacob Desvarieux, with 84 books, it looks like you read a lot! You are the
man
Press any key to continue...
|
Many of the applications we have written so far stopped when the compiler
found the return 0; line at the end of the main() function. In some
circumstances it will be necessary to stop a program from a particular function
if a bad or unexpected situation occurs. This is handled by the exit()
function. Its syntax is:
void exit(int Status);
When called from anywhere, the exit() function closes all other
functions and stops the program. The argument you pass as an integer determines
how successful the termination occurred. If the Status is passed as 0, the
program terminated successfully. Any other value of Status indicates that there
was an error during the termination. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
char __fastcall GetAnswer()
{
char Answer;
cout << "Do you consider yourself a hot-tempered individual(y=Yes/n=No)? ";
cin >> Answer;
Answer = tolower(Answer);
if( Answer != 'y' && Answer != 'n' )
exit(0);
else
return Answer;
return 'n';
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
char Ans;
Ans = GetAnswer();
if( Ans == 'y' || Ans == 'Y' )
{
cout << "\nThis job involves a high level of self-control.";
cout << "\nWe will get back to you.";
}
else
cout << "\nYou are hired!";
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
Alternatively, you can use the _exit() function to stop the program.
Its syntax is:
As opposed to the exit() function that closes all functions upon
exiting, the _exit() function stops the program without closing the other
functions. The value of the Status argument determines how the program
terminates. If the argument is passed with 0, the function would terminate
successfully. Any other value indicates an error. Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
int __fastcall NumberRequest()
{
int Number;
cout << "Type a number between 1 and 3 (included): ";
cin >> Number;
if( Number >= 1 && Number <= 3 )
return Number;
else
_exit(0);
return 0;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
int Nbr;
Nbr = NumberRequest();
cout << "Your number was: " << Nbr;
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
Notice that the sentence in the main() function executes only if the
other function did not exit because of a wrong return value.
Sometimes a program terminates with a message box sent by the operating
system. An example would be when a user is asked to provide a floating-point
number but types a string and the program is supposed to multiply the provided
value by another number. The program would stop or hang and display a message of
abnormal termination. You can also create your own abnormal termination using
the abort() function. Its syntax is:
void abort(void);
When called, the abort() function terminates the program and sends an
error message to the operating system. The OS uses different codes to identify
these types of errors. Upon exiting, the abort() function terminates with
an error code of 3. When the operating system receives it, it displays a message
box.
You can click one of the buttons. If you click Ignore, the operating system
can let you know that there was an abnormal termination.
Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
void __fastcall ProcessAnswer()
{
char Sitting;
cout << "Are you sitting down now(y/n)? ";
cin >> Sitting;
Sitting = toupper(Sitting);
if( Sitting == 'Y' )
cout << "\nWonderful!!!";
else if( Sitting == 'N' )
cout << "\nCould you please sit down for the next exercise?";
else
abort();
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
cout << "For the next exercise, you need to be sitting down\n";
ProcessAnswer();
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
If something bad happens in your program, the program is prepared to stop it.
We will learn about some of these unusual but possible situations when studying
exception handling. Nevertheless, if you suspect such a thing and would like to
stop the program, you can use one of the exit(), _exit(), or abort()
functions we have just seen. Alternatively, you can stop a program using the
terminate function. Its syntax is:
void terminate();
You can call the terminate() function the same way we did with
the exit() or abort() functions.
Borland C++ Builder ships with various types of functions to help you
customize and improve your application and its behavior. Some of the functions
are part of the C/C++ language. Some others were created by Borland. And some
other functions are built in the operating system.
Clearing the Screen With system()
|
|
When an application is running (that is, a console application), for example
while a user is performing data entry, the program processes one statement at a
time in a top-down approach. When the user finishes, you will usually display
the result on the screen. If the program is long, at one time it would fill out
the screen and this could make the displayed result confusing with the data
processing. There are two basic ways you can clear the screen in Borland C++
Builder console application. The simplest technique consists of calling the system()
function with the string argument "cls". The syntax of the system()
function is:
int system(const char *Argument);
Here is an example:
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
char FirstName[12], LastName[12];
cout << "Enter First Name: "; cin >> FirstName;
cout << "Enter Last Name: "; cin >> LastName;
system("cls");
cout << "Full Name: " << FirstName << " " << LastName;
cout << "\n\nPress any key to continue...";
getch();
return 0;
}
//---------------------------------------------------------------------------
|
Borland's Function of Clearing the Screen
|
|
Another technique used to clear the screen consists of using a special
function that a Borland created: the clrscr()
function. The clrscr() function is part of the conio library. The clrscr()
function is not part of the C++ Standard. The syntax of this function is as
follows:
void clrscr(void);
The clrscr() function does not take an argument and does not return a
value. It is simply used to empty the screen. Here is an example of using it: |
|