1. 程式人生 > >C++數字與字串的相互轉換

C++數字與字串的相互轉換

轉自https://blog.csdn.net/michaelhan3/article/details/75667066 

首先推薦用用C++的stringstream。 
主要原因是操作簡單。

數字轉字串,int float型別 同理

#include <string>
#include <sstream>

int main(){
    double a = 123.32;
    string res;
    stringstream ss;
    ss << a;
    ss >> res;//或者 res = ss.str();
    return 0;
}

字串轉數字,int float型別 同理

int main(){
    string a = "123.32";
    double res;
    stringstream ss;
    ss << a;
    ss >> res;
    return 0;
}
上面方法的優點就是使用簡單方便,確定可能會相對別的方法來說慢一點,但是一般少量的資料可以忽略該因素。

二 別的方法

2、數字轉字串: 
下面方法轉自:http://www.cnblogs.com/luxiaoxun/archive/2012/08/03/2621803.html

使用sprintf()函式

char str[10]; 
int a=1234321;

sprintf(str,”%d”,a);
char str[10]; 
double a=123.321;

sprintf(str,”%.3lf”,a);
char str[10]; 
int a=175;

sprintf(str,”%x”,a);//10進位制轉換成16進位制,如果輸出大寫的字母是sprintf(str,”%X”,a)
char itoa(int value, char string, int radix); 
同樣也可以將數字轉字串,不過itoa()這個函式是平臺相關的(不是標準裡的),故在這裡不推薦使用這個函式。

3、字串轉數字:使用sscanf()函式

char str[]=”1234321”; 
int a; 
sscanf(str,”%d”,&a); 
…………. 
char str[]=”123.321”; 
double a; 
sscanf(str,”%lf”,&a); 
…………. 
char str[]=”AF”; 
int a; 
sscanf(str,”%x”,&a); //16進位制轉換成10進位制

另外也可以使用atoi(),atol(),atof().