The C++ char_traits, to_char_type(), to_int_type and eq() 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 to_char_type() function to converts an int_type character to the corresponding char_type character and returns the result and to_int_type() to converts a char_type character to the corresponding int_type character and returns the result. The eq() to test whether two char_type characters are equal.
To show: How to use the to_char_type(), to_int_type and eq() C functions in C++ programming
// the C++ char_traits, to_char_type(), to_int_type and eq()
#include <string>
#include <iostream>
using namespace std;
int main(void)
{
char_traits<char>::char_type chr1 = '3';
char_traits<char>::char_type chr2 = 'C';
char_traits<char>::char_type chr3 = '#';
cout<<"chr1 = "<<chr1<<", chr2 = "<<chr2<<", chr3 = "<<chr3<<endl;
// converting from char_type to int_type
char_traits<char>::int_type int1, int2, int3;
int1 =char_traits<char>::to_int_type(chr1);
int2 =char_traits<char>::to_int_type(chr2);
int3 =char_traits<char>::to_int_type(chr3);
cout<<"Operation: to_int_type(character)"<<endl;
cout<<"The char_types and corresponding int_types are:"<<endl;
cout<<chr1<<" ==> "<<int1<<endl;
cout<<chr2<<" ==> "<<int2<<endl;
cout<<chr3<<" ==> "<<int3<<endl;
// int_type to char_type re conversion
char_traits<char>::char_type rev_chr1;
rev_chr1 = char_traits<char>::to_char_type(int1);
char_traits<char>::char_type rev_chr2;
rev_chr2 = char_traits<char>::to_char_type(int2);
cout<<"\nOperation: to_char_type(integer)"<<endl;
cout<<"The inverse conversion are:"<<endl;
cout<<int1<<" ==> "<<rev_chr1<<endl;
cout<<int2<<" ==> "<<rev_chr2<<endl;
// test for conversions, they are just inverse operations
cout<<"\nOperation: eq(rev_chr1, chr1)"<<endl;
bool var1 = char_traits<char>::eq(rev_chr1, chr1);
if(var1)
cout<<"The rev_chr1 is equal to the original chr1."<<endl;
else
cout<<"The rev_chr1 is not equal to the original chr1."<<endl;
// alternatively
if(rev_chr2 == chr2)
cout<<"The rev_chr2 is equal to the original chr2."<<endl;
else
cout<<"The rev_chr2 is not equal to the original chr2."<<endl;
return 0;
}
Output example:
chr1 = 3, chr2 = C, chr3 = #
Operation: to_int_type(character)
The char_types and corresponding int_types are:
3 ==> 51
C ==> 67
# ==> 35
Operation: to_char_type(integer)
The inverse conversion are:
51 ==> 3
67 ==> C
Operation: eq(rev_chr1, chr1)
The rev_chr1 is equal to the original chr1.
The rev_chr2 is equal to the original chr2.
Press any key to continue . . .