The char_traits class member, compare() C++ program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using char_traits class member, compare() to compare a string with a specified string to determine if the two strings are equal or if one is lexicographically less than the other in C++ programming

To show: How to use the char_traits class member, compare() to compare a string with a specified string to determine if the two strings are equal or if one is lexicographically less than the other in C++ programming

 

// the char_traits class member, compare() example

#include <string>

#include <iostream>

using namespace std;

 

int main(void)

{

int comp1, comp2, comp3, comp4;

 

char_traits<char>::char_type* str1 = "TEST";

char_traits<char>::char_type* str2 = "RETEST";

char_traits<char>::char_type* str3 = "RETEST";

char_traits<char>::char_type* str4 = "TESTING";

 

cout<<"str1 string is: "<<str1<<endl;

cout<<"str2 string is: "<<str2<<endl;

cout<<"str3 string is: "<<str3<<endl;

cout<<"str4 string is: "<<str4<<endl;

cout<<"\nOperation: Comparison..."<<endl;

 

comp1 = char_traits<char>::compare(str1, str2, 2);

comp2 = char_traits<char>::compare(str2, str3, 3);

comp3 = char_traits<char>::compare(str3, str4, 4);

comp4 = char_traits<char>::compare(str4, str3, 4);

 

cout<<"compare(str1, str2, 2) = "<<comp1<<endl;

cout<<"compare(str2, str3, 3) = "<<comp2<<endl;

cout<<"compare(str3, str4, 4) = "<<comp3<<endl;

cout<<"compare(str4, str3, 4) = "<<comp4<<endl;

 

return 0;

}

 

Output example:

 

str1 string is: TEST

str2 string is: RETEST

str3 string is: RETEST

str4 string is: TESTING

 

Operation: Comparison...

compare(str1, str2, 2) = 1

compare(str2, str3, 3) = 0

compare(str3, str4, 4) = -1

compare(str4, str3, 4) = 1

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index