1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
#include <iostream>
#include <sstream> // std::stringstream
#include <string> // std::string
#include <cstring> // strcpy
using namespace std;
template<class T>
void Swap( T& a , T& b )
{ T c = a ; a = b ; b = c; }
template< class T , class U >
void atob ( T& a , U& b)
{
std::stringstream into;
into.str() = "";
into << a;
into >> b;
}
void itoc( int& x , char* c )
{
std::stringstream into;
into.str() = "";
into << x;
into >> c;
}
void ctoi( char* c , int& x )
{
std::stringstream into;
into.str() = "";
into << c;
into >> x;
}
int main()
{
int x , y;
x = 7 ; y = 12;
Swap<int>( x , y );
cout << x << " " << y << endl;
// char to int
char nn = '1';
int num = 0;
atob<char,int>( nn , num );
cout << num << endl;
// int to char
num = 5;
atob<int,char>( num , nn );
cout << nn << endl;
// int to char[]
char nm[3];
num = 20;
itoc( num , nm );
cout << nm << endl;
// char[] to int
nm[0] = '1'; nm[1] = '4';
ctoi( nm , num );
// int to string
string st= "one";
atob<int,string>( num , st );
cout << st << endl;
// string to int
st = "47";
atob<string,int>( st , num );
cout << num << endl;
//char to string
char ch[] = "changeover";
st = ch;
cout << st << endl;
//string to char
st = "char turn";
char cha[st.size()+1];
strcpy( cha , st.c_str() );
cout << cha << endl;
return 0;
}
|