您好,登錄后才能下訂單哦!
如何進(jìn)行C/C++中int/long/float/double數(shù)值類型與字符串互相轉(zhuǎn)換,針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。
long long_data=-9828;
unsigned char data[4];
memcpy(data,&t,4); //將long類型的數(shù)據(jù)用4個(gè)char保存。
long my_long_data=0;
memcpy(&tt,data,4);//從4個(gè)char中還原出long類型數(shù)據(jù)。
一、int/long/float/double轉(zhuǎn)字符串
方法1:itoa, ltoa(a表示array數(shù)組的意思)
頭文件:stdlib.h
示例:
int a = 3;
long b = 23;
char buf1[30] = "";
itoa(a, buf1, 10);//10表示十進(jìn)制,buf1保存的內(nèi)容為"3"
char buf2[30] = "";
ltoa(b, buf2, 10);//10表示十進(jìn)制,buf2保存的內(nèi)容為"32"
方法2:sprintf
頭文件:stdio.h
示例:
int a = 3;
float b = 4.2f;
char buf[30] = "";
sprintf(buf, "%d,%f", a, b);//buf保存的內(nèi)容為"3,4.2",可對(duì)比printf
方法3:ostringstream
頭文件:#include <sstream>
using namespace std;
示例:
int a = 3;
float b = 4.2f;
ostringstream s1;
s1<<a<<","<<b;//可對(duì)比cout
string s2 = s1.str();//s2保存的內(nèi)容為"3,4.2"
二、字符串轉(zhuǎn)int/long/float/double
方法1:atoi,atol,atof
頭文件:stdlib.h
示例:
int a = atoi("32");
long b = atol("333");
double c = atof("23.4");
方法2:strtol, strtod
頭文件:stdlib.h
示例:
long b = strtol("333", NULL, 10);//10表示十進(jìn)制
double c = strtod("32.3", NULL);
方法3:sscanf
頭文件:stdio.h
示例:
int a;
float b;
sscanf("23 23.4", "%d %f", &a, &b);//對(duì)比scanf
方法4:istringstream
頭文件:#include <sstream>
using namespace std;
示例:
int a;
float b;
istringstream s1("23 23.4");
s1>>a>>b;//對(duì)比cin
關(guān)于如何進(jìn)行C/C++中int/long/float/double數(shù)值類型與字符串互相轉(zhuǎn)換問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。