题目要求:建立一个类Str,将一个正整数转换成相应的字符串,例如整数3456转换为字符串"3456".

题目要求:建立一个类Str,将一个正整数转换成相应的字符串,例如整数3456转换为字符串"3456".

关键:怎么将一个数字转换为字符?

 

  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. class Str  
  5. {  
  6. private:  
  7.     int num;//被转换的整数  
  8.     char s[15];//转换完的字符串  
  9. public:  
  10.     Str(int x)  
  11.     {  
  12.         num=x;  
  13.     }  
  14.     void print()  
  15.     {  
  16.         cout<<num<<endl;  
  17.         cout<<s<<endl;  
  18.     }  
  19.     void exchange()  
  20.     {  
  21.         int i=0;  
  22.         int x=num;  
  23.         while(x)  
  24.         {  
  25.             s[i]=x%10+'0';//将数字转换为字符  
  26.             x=x/10;  
  27.             i++;  
  28.         }  
  29.         s[i]='';//字符串以0结尾  
  30.         int n=i-1;  
  31.         for(int j=0;j<=n/2;j++)//将分解后的字符数组反过来排列  
  32.         {  
  33.             char c=s[j];  
  34.             s[j]=s[n-j];  
  35.             s[n-j]=c;  
  36.         }  
  37.     }  
  38. };  
  39.   
  40. int main()  
  41. {  
  42.     int n;  
  43.     cin>>n;  
  44.     Str str(n);  
  45.     str.exchange();  
  46.     str.print();  
  47.     return 0;  
  48. }  

转载:http://blog.csdn.net/wh751289288/article/details/8915446

原文地址:https://www.cnblogs.com/zhuzhudexiaoshijie/p/3328398.html