Upload
votruc
View
219
Download
3
Embed Size (px)
Citation preview
©2011 Gilbert Ndjatou Page 197
Input / Output in C++
In C++ I/O operations are performed on standard I/O classes (aka stream classes) objects.
An object must also be connected to an input/output device or file on which the physical input/output
operations are performed.
Four objects, cin, cout, cerr, and clog are predefined in the <iostream> header file.
The predefined objects cin is an instance of the class istream and is connected to the standard input
device which is the keyboard by default.
The predefined object cout is an instance of the class ostream and is connected to the standard
output device which is the monitor by default.
The predefined objects cerr and clog are instances of the class ostream and are connected to the
standard error device which is the monitor by default.
The >> operator (also known as the stream extraction operator) is defined on the class istream to
input data items of built-in types, strings, and pointer types.
The << operator (also known as the stream insertion operator) is defined on the class ostream to
output the values of arithmetic, Boolean, character, and string expressions.
After each I/O operation on an object instance of a stream class, that object can be in various states.
The Boolean-value methods in table IO1 are provided to report the states of these objects.
Table IO2 lists some of the most commonly used methods of istream class. In the description
provided, _in is an object instance of the istream (or ifstream) class; ch is a char variable, stop is a
char literal, variable, or constant; chArray is a char array; and n and offset are integers.
Table IO3 lists some of the most commonly used methods of ostream class. In the description
provided, _out is an object instance of the ostream (or ofstream) class; ch is a char variable;
chArray is a char array; and n and offset are integers.
Table IO1 Methods that report the state of an object after an I/O operation
Message Returns True if and only if
obj.good( ) All is well for stream object obj.
obj.bad( ) An unrecoverable error occurred in stream object obj.
obj.fail( ) A recoverable error occurred in stream object obj.
obj.eof( ) End-of-file mark encountered in stream object obj before finding any data.
©2011 Gilbert Ndjatou Page 198
Table IO2 istream class methods
Operation Description
_in.get( ch )
or
ch = _in.get( )
Input a single character (including white space) from _in into ch.
_in.get( chArray, n, stop )
or
_in.get( chArray, n )
Input characters from _in into chArray until n-1 characters are read or the
character stop (default value „\n‟) is encountered (but not extracted), or the end-
of-file occurs. A null character is added at the end of the input.
_in.getine( chArray, n, stop )
or
_in.getline( chArray, n )
Same as get( ), except that it removes the terminating character stop from _in.
_in.read( chArray, n ) Input characters from _in into chArray until n characters are read or the end-of-
file occurs.
_in.readsome( chArray, n ) Same as read( ), but returns the number of characters extracted.
_in.peek( ) Return the next character to be read from _in, but leave it in the stream.
_in.putback( ch ) Put the character in ch back into _in.
_in.unget( ) Put the most recent character read back into _in.
Table IO3 ostream class methods
Operation Description
_out.put( ch ) Output the single character in ch to _out.
_out.write( chArray, n ) Output n characters of chArray to _out.
_out.flush( ) Empty _out‟s output buffer.
Examples
Assume given the following definitions of variables and arrays:
char symb, text[10] = { „\0‟ }, document[ 80 ] = { „\0‟ };
1. Code segment to read the string “John Doe” from the keyboard:
cin >> text;
Input: John Doe
Array after the execution of the code:
J o h n \0 \0 \0 \0 \0 \0
©2011 Gilbert Ndjatou Page 199
2. Code segment to read the string “John Doe” from the keyboard:
for( int c = 0 ; c < 9 ; c++ )
{
cin.get( symb ); // can also be written as: symb = cin.get( );
text[ c ] = symb;
}
Input: John Doe
Array after the execution of the code:
J o h n D o e \0 \0
3. Code segment to read the string “John Doe” from the keyboard:
cin.get( text , 9 , „\n‟ ); // can also be written as: cin.get( text , 9 );
Input: John Doe
Array after the execution of the code:
J o h n D o e \0 \0
4. Code segment to read a sequence of 79 characters from the keyboard or until the END-OF-FILE
character is entered:
int c = 0 ;
cin.get( symb );
while( c < 79 && !cin.eof( ) )
{
text[ c++ ] = symb;
cin.get( symb );
}
5. Code segment to out the string “Error: invalid character” to the monitor:
cerr >> “Error: invalid character”; // this necessary when you make output redirection
6. Code segment to output the string in the array text[ ] to the monitor:
cout << text; // can also be written as: cout.write( text , 8 );
©2011 Gilbert Ndjatou Page 200
File Input - Output
File input are performed on object instances of the class ifstream and
File output are performed on object instances of the class ofstream.
ifstream is a derived class of the class istream:
o All the methods of the istream class (including those in tables OI1 and OI2) are also the
methods of the ifstream class.
o The stream extraction operator >> can also be used to perform input from object instances of
the ifstream class.
ofstream is a derived class of the class ostream:
o All the methods of the ostream class (including those in tables OI1 and OI3) are also the
methods of the ofstream class.
o The stream insertion operator << can also be used to perform output to object instances of the
ofstream class.
The definitions of ifstream and ofstream classes are provided in the header file <fstream>:
o You must therefore include this header file in all program in which file I/O are performed.
Formatted output are performed with a file output stream object in the same way that it is done with
cout stream object:
o Just replace cout with the name of your object in the output statement.
You connect an input/output stream object to a file on which the physical input/output
operations are performed by using the open method as follows:
<stream-object>.open( <name-of-file>, <opening-mode>);
Where:
<stream-object> is the name of the stream object.
<name-of-file> is the filename specification of the input/output file.
<opening-mode> is the file-opening mode.
The file-opening modes are listed in table OI4.
Examples
1. // fin is my input stream object and program.dat is my input file
ifstream fin;
fin.open(“progam.dat”, ios::in); or fin.open(“progam.dat”);
©2011 Gilbert Ndjatou Page 201
2. // fout is my output stream object and program.out is my output file
ofstream fout;
fout.open(“progam.out”, ios::out); or fout.open(“progam.out”);
3. // fapp is my output stream object and program.out is my output file
ofstream fapp;
fapp.open(“progam.out”, ios::app);
After you are done doing I/O operations on an I/O stream object, use the member function close( ) to
close the corresponding file as follows:
<stream-object>.close( );
Examples
1. fin.close( );
2. fout.close( );
3. fapp.close( );
Table IO4
Mode Description
ios :: in This is the default mode for ifstream objects. Open a file for input, non- destructively,
with the read position at the beginning of the file.
ios :: trunc Open a file and delete any contents it contains.
ios :: out This is the default mode for ofstream objects. Open a file for output using ios::trunc.
ios :: app Open a file for output, but non-destructively, with the write position at the end of the file.
ios :: ate Open an existing file with the read position (for ifstream objects) or write position (for
ofstream objects) at the end of the file.
ios :: binary
Open a file for which I/O will be done in binary mode. Bytes are read from the file into
a char array using the read method and written from a char array to the file using the
write method.
©2011 Gilbert Ndjatou Page 202
Example IO1
ifstream fin; // fin is my input stream object
ofstream fout; // fout is my output stream object
fin.open(“progam.dat”, ios::in); // program.dat is my input file
fout.open(“progam.out”, ios::out); // program.out is my output file
/*-----------------read two integer values from the input file program.dat ---------------------*/
int num1, nm2;
fin >> num1 >> num2;
/*---------compute their sum and write the result in the output file program.out -------------*/
fout << endl << “num1=\t” << num1 << endl << “num2=\t” << num2
<< endl << “Their sum is:\\t” << (num1 + num2) << endl;
/*-------------------------------close the input and the output files----------------------------------*/
fin.close( );
fout.close( );
©2011 Gilbert Ndjatou Page 203
Example IO2
/**************************************************************************
Program to read an employee’s pay rate and the number of hour of work
And compute his gross pay using file I/O: the name of the input file is
“prog.dat” and the name of the output file is “prog.out”
***************************************************************************/
#include <iostream> // in order to use cout for putput
#include <fstream> // for file I/O
#include <iomanip> // for formatted output
#include <cstdlib> // for exit function
using namespace std;
int main()
{
ifstream finput; // finput is the input stream object
ofstream foutput; // foutput is the output stream object
double payRate; // to hold the pay rate
int hours; // to hold the number of hours
/*---------- connect the I/O stream objects to the files ------------*/
finput.open( “prog.dat” );
if( finput.fail( ) )
{
cerr << endl << “Failure opening input file”;
exit( 1 ); // terminate the program
}
foutput.open( “prog.out” );
if( foutput.fail( ) )
{
cerr << endl << “Failure opening output file”;
exit( 2 ); // terminate the program
}
foutput.setf(ios :: fixed); // for formatted output to the file
foutput.setf(ios :: showpoint); // for formatted output to the file
/*----read the pay rate and the number of hours from the input file---*/
finput >> payRare >> hours;
/*-----compute and print the gross pay into the output file ----------*/
foutput << setprecision(2);
foutput << endl << setw(10) << “Pay Rate:” << setw(6) << payRate;
foutput << endl << setw(10) << “Hours:” << setw(6) << hours;
foutput << endl << setw(10) << “Gross Pay:”
<< setw(6) << (payRate * hours);
finput.close( );
foutput.close( );
return 0;
}
©2011 Gilbert Ndjatou Page 204
Exercise IO1
The information about a product consists of its ID number, name, unit price, and quantity. Define a
structure named ProductInfo to hold its ID number, name, and price ( price = unit price times quantity)
and then do the following:
1. Define an array productList[ 10 ] of ten ProductInfo structures.
2. Read from the input file, product.data, the ID numbers, names, unit prices, and quantities of these
ten products and build the array productList.
3. Output into the file product.output a table consisting of the products IDs, names, and prices (with
appropriate headings).
Overloading the Stream Insertion Operator << and the Stream
Extraction Operator >>
The stream insertion operator << is a function with two parameters: an object of the class
ostream (on which the output is performed) and the object to be output.
The stream extraction operator >> is a function with two parameters: an object of the class
istream (on which the input is performed) and the object to be input.
Both the stream input and the stream output operators can be implemented as ordinary functions or
as friend functions of the class of the object to be input/output.
Example IO3 Overloading the Insertion and the Extraction Operators as friend Functions
The following class Demo13A is the class Demo13 defined in example M8 with the insertion and the
extraction operators declared as friend functions of the class Demo13A:
class Demo13A
{
public:
Demo13A (int n1 = 0, int n2 = 0); // constructor
int getFirst( ); // returns the value of the first member variable
int getSecond( ); // returns the value of the second member variable
Demo13A operator +( const Demo13A & rightOp );
Demo13A & operator ++( );
friend ostream &operator <<(ostream &outs , const Demo13A &obj);
friend istream &operator >>(istream &ins , Demo13A &obj);
private:
int val1;
int val2;
};
©2011 Gilbert Ndjatou Page 205
/*----------------------------------------------- operator << -----------------------------------------------------*/
/* Receives an ostream object and a Demo13A object.
Output to the ostream object the values of the member variables of the Demo13A object.
Returns a reference to the ostream object
*/
ostream &operator <<(ostream &outs , const Demo13A &obj)
{
outs << endl << “first value is:\t” << obj.val1
<< endl << “second value is:\t” << obj.val2;
return( outs );
}
/*------------------------------------------------ operator >> ----------------------------------------------------*/
/* Receives an istream object and a reference to a Demo13A object.
Input from the istream object the values for the member variables of the Demo13A object.
Returns a reference to the input stream object
*/
istream &operator >>(istream &ins , Demo13A &obj)
{
ins >> obj.val1 >> obj.val2;
return( ins );
}
/*--------------------------------------- Using the overloaded operators --------------------------------------*/
/* read input from the keyboard and send output to the file prog.out */
#include <fstream>
#include <iostream>
using namespace std;
int main( )
{
ofstream foutput; // foutput is my output stream object
Demo13A tobj, sobj, robj;
foutput.open( “prog.out” );
/*---------------------------read the values for the objects from the keyboard-------------------------*/
cin >> tobj >> sobj;
/*---------------- perform some computations and print the results in the file ----------------------*/
foutput << ++tobj;
robj = ++sobj + Demo13A( 21 , 15 );
foutput << sobj << robj;
foutput.close( );
return 0;
}
©2011 Gilbert Ndjatou Page 206
Notes
We are able to use the overloaded insertion operator << more than once in a statement (such as
foutput << sobj << robj) because the function (operator <<) returns a reference to the ostream
object which is used again as an operand for the next insertion operator.
Similarly, we are able to use the overloaded extraction operator >> more than once in a statement
(such as cin >> tobj >> sobj) because the function (operator >>) returns a reference to the
istream object which is used again as an operand for the next extraction operator.
Exercise IO2
Create the class Triplet2A by adding to the class Triplet2 that you have defined in exercise M8 the
declarations of the insertion and the extraction operators as friend functions of the class Triplet2A and
then do the following:
A. Write the definitions of the insertion and the extraction operators.
B. Write the definition of function main that does the following:
1. Read values into three objects of the class Trilet2A and initialize the fourth object with (10, 20,
30).
2. Subtract the second object from the first and print the result.
3. Compare the first Triplet2A object to the third and if it is <= to the third output the string “It is
my lucky day”; otherwise, output the string “I will do better next time”.
4. Increment the third object and print the result.
5. Subtract the Triplet2A object (12, 15, 18) from the fourth one (which has been incremented) and
print the result.
Note: Input data are read from the file Triplet2A.dat and the output are written into the file
Triplet2A.output.
Overloading the Insertion and the Extraction Operators as Ordinary
Functions
In order to overload the extraction operator as an ordinary function, you must first define a read
(input) member function of the class with an istream object as argument, and then call that member
function in the definition of the overloaded extraction operator.
In order to overload the insertion operator as an ordinary function, you must first define a print
(output) member function of the class with an ostream object as argument, and then call that member
function in the definition of the overloaded insertion operator.
Example IO4 Overloading the Insertion and the Extraction Operators as ordinary Functions
The following class Demo13B is the class Demo13 (defined in example M8) with two additional
member functions print( ) and a read( ).
©2011 Gilbert Ndjatou Page 207
class Demo13B
{
public:
Demo13B (int n1 = 0, int n2 = 0); // constructor
int getFirst( ); // returns the value of the first member variable
int getSecond( ); // returns the value of the second member variable
Demo13B operator +( const Demo13B & rightOp );
Demo13B & operator ++( );
void print( ostream &outs ); // outputs the values of the data members
void read( istream &ins ); // reads the values of the data members
private:
int val1;
int val2;
};
/*--------------------------------- Member function print( ) -------------------------------------------*/
/* Receives an ostream object and output the values of the data members to it */
void Demo13B :: print( ostream &outs )
{
outs << endl << “first value is:\t” << val1 << endl << “second value is:\t” << val2;
}
/*------------------------------------- Member function read( ) ----------------------------------------*/
/* Receives an istream object and input from this object the values for the data members */
void Demo13B :: read ( istream &ins )
{
ins >> val1 >> val2;
}
/*---------------------------------------- operator << -----------------------------------------------------*/
/* Receives an ostream object and a Demo13B object.
Output to the ostream object the values of the member variables of the Demo13B object.
Returns a reference to the ostream object
*/
ostream &operator <<(ostream &outs , const Demo13B &obj)
{
obj.print( outs );
return( outs );
}
©2011 Gilbert Ndjatou Page 208
/*---------------------------------------- operator >> ----------------------------------------------------*/
/* Receives an istream object and a reference to a Demo13B object.
Input from the istream object the values for the member variables of the Demo13B object.
Returns a reference to the istream object
*/
istream &operator >>(istream &ins , Demo13A &obj)
{
obj.read( ins );
return( ins );
}
Exercise IO3
1. Define the class Triplet2B by adding to the class Triplet2 that you have defined in exercise M8 two additional
member functions, void read( istream &ins ) and void print(ostream &outs). Member function read( )
inputs from the object that it receives as argument the values for the data members and print( )
outputs the values of the data members to the object that it receives as argument.
2. Write the definitions of these member functions.
3. Write the definitions of the overloaded insertion and extraction operators as ordinary functions.
©2011 Gilbert Ndjatou Page 209
C-Style Strings and the Standard string Class
The C++ programming language does not have a predefined (or basic) string data type.
String processing capabilities are provided through C-style strings (or C-strings) and the standard
string class.
C-Style Strings
A C-style string is an array of characters terminated by the null character („\0‟).
Example CS1
The following are examples of C-style strings:
1. char name[10] = “John Doe”;
name
2. char greeting[ ] = “Hello there”;
greeting
3. With the following declaration statement, the string constant will be stored into an array in the
text segment and its address (the address of its first character) will be stored into the pointer
variable address (memory location) created in the stack.
char * address = “300 Pompton Road, Wayne, NJ 07470”;
Note
For efficiency reasons, it is a good programming practice to always declare string constants
using character pointer variable as in example 3 above or as a static arrays as follows:
static char address[ ] = “300 Pompton Road, Wayne, NJ 07470”;
J o h n D o e \0 \0
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
H e l l o t h e r e \0
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]
©2011 Gilbert Ndjatou Page 210
The length of a C-style string is the number of characters that it contains (without counting the null
character). For example, the length of the string in example 1 is 8; that of the string in example 2 is
11, and that of the string in examples 3 is 33.
The null string is the string with length 0.
A C-style string is referred to as a variable-length string because the length of a string varies from
0 to the n -1 where n is the size of the array that holds the string.
Input/Output of C-Style Strings
Output of C-style strings are performed either by using the stream insertion operator << or the
ostream member function write( ).
Example CS2
Assume given the following declarations of C-strings:
char greeting[ ] = “Hello there”;
char * address = “300 Pompton Road, Wayne, NJ 07470”;
1. cout << endl << greeting; // output: |Hello there
2. cout.write( address, 33 ); // output: |300 Pompton Road, Wayne, NJ 07470
3. cout.write( address, 16 ); // output: |300 Pompton Road
You may also use the ostream member function put( ) to output the characters of a C-style string
one character at a time as in the following example:
for( int ct = 0 ; address[ ct ] != „\0‟ ; ct++ )
cout.put( address[ ct ] );
Strings of characters without a white space (newline, space, tab, . . ., etc) may be input into a C-style
string by using the stream extraction operator >>.
Example CS3
char newString[ 10 ];
cin >> newString;
input: |John Doe
newString
J o h n \0 \0 \0 \0 \0 \0
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
©2011 Gilbert Ndjatou Page 211
Input may also be performed by using one of the istream member functions in table IO2.
Example CS4
char myString[ 15 ], yourString[ 15 ];
/*------read 14 characters from the standard input into the string myString ------------*/
cin.getline( myString, 14 );
/*------read 14 characters from the standard input into the string yourString ----------*/
for( int ct = 0 ; ct < 14 ; ct++ )
yourString[ ct ] = cin.get( );
yourString[ 14 ] = „\0‟;
Processing C-Style Strings
C-style strings may be processed using either arrays subscripting or pointer arithmetic. However,
most programmers prefer to use pointer arithmetic.
Example CS5
/*---------------- function to compute the length of a string- subscripting version -----------*/
int computeLength1( const char * str )
{
int ct = 0;
while( str[ ct ] != „\0‟ )
ct++ ;
return( ct );
}
/*---------- function to compute the length of a string- pointer arithmetic version -----------*/
int computeLength2( const char * str )
{
char * pt;
for( pt = str ; * pt != „\0‟ ; pt++ );
return( pt - str );
}
©2011 Gilbert Ndjatou Page 212
Example CS6
/*---------------- function to copy a string to another string- subscripting version -----------*/
/* it is assumed that the array strTo[ ] has enough elements to hold the string that is copied */
void copyString1( char * strTo, const char * strFrom )
{
for( int ct = 0; ( strTo[ ct ] = strFrom[ ct ] ) != „\0‟ ; ct++ );
}
/*---------- function to copy a string to another string - pointer arithmetic version -----------*/
/* it is assumed that the array strTo[ ] has enough elements to hold the string that is copied */
void copyString2( char * strTo, const char * strFrom )
{
While( ( * strTo = * strFrom ) != „\0‟ )
{
strTo++ ;
strFrom++ ;
}
}
Library Functions for Processing C-Style Strings
Several functions for processing C-style strings are provided in various C libraries. The function
prototypes of some of these functions (with their descriptions) are provided in tables CS1, CS2, and
CS3.
Note
Some of these functions return the address of a string. However, they may be called as void
functions.
Example CS7
1. Assume given the following strings declarations:
char str1[ 10 ],
str2[12] = “Bottle”,
str3[ ] = “neck”;
strcpy( str1, str2 ); // function strcpy( ) is called as a void function
strcat( str2, str3 ); // function strcat( ) is called as a void function
©2011 Gilbert Ndjatou Page 213
str1
str2
2. Read a string and convert lowercase characters in the string to uppercase:
char myString[ 21 ]; // maximum length of the string is 20
cin.getline( myString, 20 ); // read a maximum of 20 characters
for( int ct = 0; ct < strlen( myString ) ; ct++ )
if( islower( myString[ ct ] )
mySring[ ct ] = toupper( myString[ ct ] );
Exercise CS1
1. Write a function that, given a string of lowercase and uppercase letters, returns a copy of the string in
all lowercase letters.
2. Write a function that, given a first name and a last name, returns another string consisting of the last
name followed by a comma and a space, followed by the first name.
3. Write a function that, given a string of characters, returns true if all the characters in the string are
digits, and false otherwise.
4. A string is a palindrome if it reads the same way forward and backward. Examples: madam,
45254. Write a function that, given a string, returns true if it is a palindrome, and false otherwise.
Table CS1
Header file: <cstring>
Function Description
char *strcat( char *s1, const char *s2 );
Appends the string s2 to s1. The first character of s2
overwrites the terminating null character of s1. The new
string s1 is returned.
char *strcpy( char *s1, const char *s2 ); Copies the string s2 into the character array s1. String s1
is returned.
int strcmp( const char *s1, const char *s2 );
Compares the string s1 with the string s2. Returns a
negative value if s1 < s2; 0 if s1 = = s2; and a positive
value if s1 > s2.
int strlen( const char *s ); Returns the length of string s.
char strstr( const char *s1, const char *s2);
Searches string s1 for the first occurrence of string s2.
Returns the address of the first character of this
occurrence or null if s2 is not found in s1.
B o t t l e \0 \0 \0 \0
B o t t l e n e c k \0 \0
©2011 Gilbert Ndjatou Page 214
Table CS2
Header file: <cstdlib>
Function Description
double atof( const char *s ); Converts string s to a double precision value (if possible)
and returns that value.
int atoi( const char *s ); Converts string s to an integer (int ) value (if possible) and
returns that value.
long int double atol( const char *s ) Converts string s to an integer (long int) value (if possible)
and returns that value.
Table CS3
Header file: <ctype>
Function Description
bool islower( const char ch ); Returns true if the character in variable ch is in lowercase; and false
otherwise.
bool isupper( const char ch ); Returns true if the character in variable ch is in uppercase; and false
otherwise.
bool isspace( const char ch ); Returns true if the character in variable ch is a white space (space, new
line, return character); and false otherwise.
bool isdigit( const char ch ); Returns true if the character in variable ch is a digit (0, 1, 2, 3, 4, 5, 6,
7, 8, or 9); and false otherwise.
bool isalpha( const char ch ); Returns true if the character in variable ch is a letter of the alphabet;
and false otherwise.
bool isalnum( const char ch ); Returns true if the character in variable ch is a digit or a letter of the
alphabet; and false otherwise.
char tolower (char ch); Returns the ascii code for the lowercase letter of the letter in ch.
char toupper (char ch); Returns the ascii code for the uppercase letter of the letter in ch.
Arrays of C-Style Strings
An array of C-style strings is defined by using a two-dimensional array of characters as in the
following example.
Example CS8
char nameList[ 10 ][ 15 ]; //array of 10 names – a name has a maximum of 14 characters
The strings in the array are accessed by using the pointers:
nameList[ 0 ], nameList[ 1 ], nameList[ 2 ], nameList[ 3 ], nameList[ 4 ], nameList[ 5 ],
nameList[ 6 ], nameList[ 7 ], nameList[ 8 ], and nameList[ 9 ].
©2011 Gilbert Ndjatou Page 215
The code segment for reading strings of characters without white spaces into the array follows:
for( int ct = 0 ; ct < 10 ; ct++ )
cin >> nameList[ ct ];
The code segment for reading strings of 14 characters into the array follows:
for( int ct = 0 ; ct < 10 ; ct++ )
cin.getline( nameList[ ct ], 14 );
The code segment to output the strings of the array above follows:
for( int ct = 0 ; ct < 10 ; ct++ )
cout << endl << nameList[ ct ];
An array of string constants is better stored in memory by using an array of pointer variables as in
the example that follows:
Example CS9
static char * weekdayList[ 7 ] = { “Sunday”, “Monday”, “Tuesday”, “Wednesday”,
“Thursday”, “Friday”, “Saturday”
};
The following code segment displays the string constants in the array weekdayList[ ]:
for( int ct = 0 ; ct < 7 ; ct++ )
cout << endl << weekdayList[ ct ];
It is represented in memory as follows:
Exercise CS2
1. Write a function that accepts the number of a day and returns the name of that day.
2. Write a function that accepts the name of a day and returns the number of that day.
weekdayList[ 0 ] S u n d a y \0
weekdayList[ 1 ] M o n d a y \0
weekdayList[ 2 ] T u e s d a y \0
weekdayList[ 3 ] W e d n e s d a y \0
weekdayList[ 4 ] T h u r s d a y \0
weekdayList[ 5 ] F r i d a y \0
weedayList[ 6 ] S a t u r d a y \0
©2011 Gilbert Ndjatou Page 216
The Standard string Class
The standard C++ string class defined in the <string> header file provides a large collection of
string operations.
String Constructors
A string object can be defined in many ways. The list of constructors is provided in table SC1.
Example SC1
1. string name1; // string object name1 is initialized to the null string “”
2. string name2( “John Doe” ); // string object name2 is initialized to the C-string “John Doe”
3. string name3( name2 ); // string object name3 is initialized to “John Doe”
4. char cname[ ] = “Applebee”;
string nam4( cname, 5 ); // string object name4 is initialized with “Apple”
5. string snore( 5, „z‟ ); // string object snore is initialized with “zzzzz”
6. string name5( name2, 5, 2 ); // string object name5 is initialized to “Do”
7. string name6( name2, 5 ); // string object name6 is initialized to “Doe”
Table SC1
String Constructors Descriptions
string( ); Initialize a string object to the null string.
string( char *s ); Initialize a string object with a C-string.
string( string &str ); Copy constructor.
string( char str[ ] , int n ); Initialize a string object with the first n characters of the array str[ ].
srting( int n , char ch ); Initialize a string object with n copies of the character ch.
string( string str, int spos, int len); Initialize a string object with the substring of the string str with length
len, that starts in position spos.
string( string str, int spos ); Initialize a string object with the substring of the string str that starts in
position spos to the end of the string.
Methods that Provide Information about a string Object’s Storage
Some of these methods are described in table SC2.
©2011 Gilbert Ndjatou Page 217
Table SC2
Methods Descriptions
s.capacity( ) Returns the capacity (size) of the storage allocated for string object s.
s.size( ) or s.lenght( ) Returns the length of string object s.
s.empty( ); Returns true if string object s is the null string; and false otherwise.
s.max_size( ); Returns the largest possible capacity of string object s.
string Objects Input/ Output
string objects are output (to a file or the standard output) by using the stream insertion operator <<.
Character strings (with no white spaces) can be input into string object with the stream insertion
operator <<.
Function getline( ) with the prototype that follows, can also be used to input a character string into
a string object.
void getline( istream ins , string s , char term = ‘\n’ );
getline extracts characters from the stream object ins and stores them into string s until character
term is encountered or the maximum possible number of characters are read. Character term is
removed from the buffer, but it is not stored in s.
Example SC2
1. string str1;
cin >> str1;
input: |John Doe string str1 will contain the string “John”.
2. string str2;
getline( cin , str2 );
input: |John Doe string str2 will contain the string “John Doe”.
Comparing Strings
A string object can be (lexicographically) compared to another string object or a C-style string by
using the compare( ) method or one of the following overloaded relational operators (with their
obvious meanings) : <, <=, >, >=, = =, and !=.
s.compare( str ) returns a negative value if s is less than str; 0 if they are equal; and a positive value
if it is greater.
©2011 Gilbert Ndjatou Page 218
Concatenation, Assignments and Subscripting
The + operator is overloaded to concatenate a string object to another string object, a C-style string,
or a character.
The assignment operator = is also overloaded to assign a string object, a C-style string, or a
character to a string object.
The compound assignment += appends an object string, a C-style string, or a character to a string
object.
Individual characters of a string object can be accessed by using the subscript operator in the same
that we use the subscript operator on C-style strings.
Example SC3
string lastName = “Doe”,
greeting( “Hello” ),
firstName( “John” ),
name;
char newString[ ] = “ World!”;
name = lastName + „,‟ + „ „ + firstName;
greeting += newString;
cout << firstName + „ „ + lastName;
lastName[ 0 ] = „J‟;
©2011 Gilbert Ndjatou Page 219
Execution of a C++ Program
The execution of a C/C++ program starts with a function called main with the following prototype:
int main (int argc, char *argv[])
argc is the number of command-line arguments, and
argv[] is an array of pointers to the arguments
You execute a C/C++ program by typing a command line that consists of the name of the
executable file of the program followed by other arguments to be passed to function main as
follows:
For example, the command line: computepay.bin John Doe 12.5 40
has the following 5 arguments:
“computepay.bin” (the name of the program)
“John”
“Doe”
“12.5”
“40”
Arguments are C-style strings that are passed to function main by using its value parameters, argc
and argv[ ].
For the command line argument above,
argc is initialized with 5
the elements of the array of pointers argv[] are initialized with the addresses of the C-style
strings (arguments) as follows:
argv [0] computepay.bin
[1] John
[2] Doe
[3] 12.5
[4] 40
[5]
When a C/C++ program is started by the operating system, a special start-up routine is called before
function main is called.
This start-up routine takes values from the operating system (the command-line arguments and the
environment variables) and sets things up so that function main is called as shown above.
Null
NULL
©2011 Gilbert Ndjatou Page 220
Example EP1
The following program is executed with command line arguments that consist of the first and the last
name of an individual, followed by his pay rate and number of hours of work in this order. The program
computes the gross pay and outputs the last and the first names of this individual followed by his gross
pay.
/*---------------------------------------------------------------------------------------------------------------------*/
#include <iostream>
#include <cstdlib>
using namespace std;
int main (int argc , char *argv[ ])
{
int hours;
double payRate;
/*------------------- make sure that you have the proper number of arguments -----------------------*/
if (argc != 5)
{
cerr << endl << “you did not provide enough arguments”;
exit ( 1);
}
/*------------- convert the pay rate to floating point and the number of hours to integer ------------*/
payRate = atof (argv[ 3 ];
hours = atoi (argv[ 4 ];
/*------------ compute the gross pay and print it with the name of the employee ----------------------*/
cout << endl << argv [2] << “, ” << argv[1]
<< endl << “Your gross pay is:\t” << payRate * hours;
return 0;
}
Exercise EP1
Write the main function of a program that is executed with a command line with four arguments: the
second argument is an integer value, the third a floating point value, and the last one another integer
value. The program multiplies the first two values, adds the third one, and prints the result.
This program may be executed as follows: prog.bin 12 24.5 10
©2011 Gilbert Ndjatou Page 221
Programmer-Defined Data Types
In C+, a new type can be created by using the typedef mechanism or an enumeration type.
You use the typedef mechanism to create a new type by giving a new name to an existing type as
follows:
typedef <old-data-type> <new-Name>;
Example DDT1
1. typedef double real;
real fnmu1, fnum2 = 12.5;
2. The data type of the elements of an array can be defined as followed:
typedef int elementType;
elementType list[ 20 ];
3. A typedef can be used to eliminate the repeated use of the asterisk in the declaration of a pointer
variable as follows:
typedef int * integerPointer;
typedef double * doublePointer;
integerPointer ipt1, ipt2;
doublePointer dpt1, dpt2;
Enumeration types are used to create data types whose constant data are identifiers.
Each identifier (constant data) in the set of values is assigned an integer value.
When an expression is evaluated, each identifier (constant data) in that expression is replaced by its
value.
Example DDT2
1. enum days {Mon, Tue, Wed, Thu, Fri, Sat, Sun}; // Mon = 0, Tues = 1, . . ., etc.
days today, yesterday = Wed;
today = yesterday + 1;
cout << endl << “enter a day of the week code: 0 – 6 :\t”;
cin >> oneDay;
if (oneDay < Mon || oneDay > Sun)
cout << endl << “invalid day code”;
©2011 Gilbert Ndjatou Page 222
/*---- read the 5-day deposits to a bank by a store into the array deposits [ ] ------*/
double deposits [5];
for (days dayNdx = Mon; dayNdx <= Fri; dayNdx ++)
{
cout << endl << “enter deposit for day:\t” << dayNdx + 1;
cin >> deposits [dayNdx];
}
2. enum colors {red = 1, blue = 1000, green = 10000};
colors CarColor;
cout << endl << “enter a car color: 1 for red, 1000 for blue, 10000 for green:\t”;
cin >> CarColor;
if (CarColor != red && CarColor != blue && CarColor != green)
cout << endl << “invalid car color”;