Wednesday, 8 June 2011
The following example shows strcpy( ), strcat( ), strcmp( ), and strlen( ) in action:
The following example shows strcpy( ), strcat( ), strcmp( ), and strlen( ) in action:
// Demonstrate the basic null-terminated string functions.
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char strA[7] = "Up";
char strB[5] = "Down";
char strC[5] = "Left";
char strD[6] = "Right";
cout << "Here are the strings: " << endl;
cout << "strA: " << strA << endl;
cout << "strB: " << strB << endl;
cout << "strC: " << strC << endl;
cout << "strD: " << strD << "\n\n";
// Display the length of strA.
cout << "Length of strA is " << strlen(strA) << endl;
// Concatenate strB with strA.
strcat(strA, strB);
cout << "strA after concatenation: " << strA << endl;
cout << "Length of strA is now " << strlen(strA) << endl;
// Copy strC into strB.
strcpy(strB, strC);
cout << "strB now holds: " << strB << endl;
// Compare strings.
if(!strcmp(strB, strC))
cout << "strB is equal to strC\n";
int result = strcmp(strC, strD);
if(!result)
cout << "strC is equal to strD\n";
else if(result < 0)
cout << "strC is less than strD\n";
else if(result > 0)
cout << "strC is greater than strD\n";
return 0;
}
The output is shown here:
Here are the strings:
strA: Up
strB: Down
strC: Left
strD: Right
Length of strA is 2
strA after concatenation: UpDown
Length of strA is now 6
strB now holds: Left
strB is equal to strC
strC is less than strD
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment