欢迎来到 安卓源码空间!
安卓源码空间

                                C++ 数字与字符串之间相互转换(多种方法)



使用系统提供的库函数

1.字符串传数字

 (1)、使用stoi()

string s("12345"); long long a = stoi(s); cout << a << endl; 

 (2)、使用atoi()

char str3[10] = "3245345"; //数字简单,所以转数字一个参数  long long a = atoi(str3); cout << a << endl; 

 (3)、使用 sscanf() 映射

long long c = 0; char str5[10] = "661234544"; sscanf(str5, "%d", &c); //从左至右,字符串转数字  cout << c << endl; 

 (4)、自己写一个简单的

//字符串转为整数,通过减'0'字符,底层用ASCII码相减  
void myAtoi(
 char str[],long long& m)
 { int i(0); 
 int temp = 0; 
 while(str[i] != '\0'){
 temp = temp*10 + (str[i] -'0'); ++i;
      } 
     m = temp; //转换后赋值给m 
 } 

2.数字转字符串

 (1)、使用c++里的to_string()

long long m = 1234566700; string str = to_string(m); //系统提供数字转字符  cout << str << endl; 

 (2)、使用itoa()

int n = 100; char str2[10]; //字符串比较麻烦,所以转字符串三个参数,我是这么记得(手动滑稽)  
itoa(n,str2,10); //第一个参数为整数,第二个为字符串(char*),第三个为进制  cout << str2 << endl; 

 (3)、使用sprintf() 映射

long long b = 1234560; char str4[10] = {0}; sprintf(str4, "%d", b); //从右至左,把数转换为字符串  cout << str4 << endl; 

 (4)、自己写一个简单的

//整数转为字符串:通过加 '0'字符 
  void myItoa(long long n, char str[])
 { 
 char temp[MAX]{0}; 
 int i(0); 
 int j = 0;
     while(n){ 
        temp[i++] = n%10 + '0';
         n /= 10;
      } 
 //此时为逆序,需要调整为正序  
 //cout <<  temp << endl;
          while(i>0) 
           str[j++] = temp[--i]; 
 // cout << str << endl; 
 } 

————————————————

                            版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
                        
                            原文链接:https://blog.csdn.net/weixin_43971252/article/details/104063490

copyright@ 2020-2028  安卓源码空间网版权所有   

备案号:豫ICP备2023034476号-1号