|
Character Array Examples
1. Using character array initialization
% cat strtest.cpp
// C-style character string array example
#include <iostream>
using namespace std;
int main()
{
// const int NUMDISPLAY = 15;
int i;
// char q, strtest[] = {'T', 'h', 'i', 's', ' ', 'i', 's',
' ', 'a',
//
' ', 't', 'e', 's', 't', '\0'};
char q, strtest[] = "This
is a test";
cout << strtest << endl;
//
use function strlen to get the number of characters in
the string
// not including the '\0' null character
cout << "The length of the string = " <<
strlen( strtest ) << endl;
for ( i = 0; i < strlen( strtest );
i++ )
{
q = strtest[i];
if (q == 't' || q == 'e' || q == 's')
cout << q;
}
cout << endl;
return 0;
}
% g++ strtest.cpp
% a.out
This is a test
The length of the string = 14
sstest
2. Using cin.getline to input a character array from the
keyboard
% cat strtest1.cpp
// C-style character string array example
#include <iostream>
using namespace std;
int main()
{
const int NUMDISPLAY = 15;
int i;
char q, strtest[NUMDISPLAY];
cout << "Enter a character string:\n";
//cin >> strtest;
cin.getline(strtest, NUMDISPLAY);
cout << strtest << endl;
//
use function strlen to get the number of characters in
the string
// not including the '\0' null character
cout << "The length of the string = " <<
strlen( strtest ) << endl;
for ( i = 0; i < strlen( strtest );
i++ )
{
q = strtest[i];
if (q == 't' || q == 'e' || q == 's')
cout << q;
}
cout << endl;
return 0;
}
% g++ strtest1.cpp
% a.out
Enter a character string:
Fido Rex
Fido Rex
The length of the string = 8
e
% a.out
Enter a character string:
This here dog has fleas!
This here dog
The length of the string = 14
see
|