boost中型別轉換學習

2021-07-03 21:55:04 字數 3891 閱讀 7942

型別轉換在很多時候需要使用上,方便且安全的轉換是很有必要的。從c語言的一些api到c++中提供的stringstream流都有很多方式可以實現,了解他們的特點可以讓我們在日常編碼中編寫出漂亮的**。

一、c語言中常用的型別轉換

char szbuf[100];

int nvalue = 100000000;

sprintf_s(szbuf, sizeof(szbuf), "%d", nvalue);

printf("%s\n", szbuf);

float fvalue = 1.2f;

sprintf_s(szbuf, sizeof(szbuf), "%f", fvalue);

printf("%s\n", szbuf);

char szoutbuf[100] = ;

sscanf_s(szoutbuf, "%f", &fvalue);

printf("%f\n", fvalue);

// 嘗試從以%f格式化乙個int型別的數字

通過sprintf和sscanf可以從數值型別到字串型別的轉換, 標頭檔案中包含大量資料轉換的api封裝,比如_i64toa、

_itoa、strtod、strtol、

_fcvt

等等。詳細可參考msdn手冊。

二、c++中通過stringstream流進行資料型別轉換

//記得加上標頭檔案

#include #include using namespace std;

string strvalue;

string strothervalue;

stringstream ssio;

int nvalue = 123;

ssio << nvalue << " " << nvalue + 1; // 往stringstream流中寫入123 124

string strbuf = ssio.str(); // 從stringbuf中獲取內容

cout << "stringstream buffer:" << strbuf << endl; // 123 124

ssio >> strvalue; // 將數值從ssio流中讀取到strothervalue中

int nstate = ssio.rdstate(); // goodbit 0x00

cout << "stringstream state:" << nstate << endl;

ssio >> strothervalue; // 將數值從ssio流中讀取到strothervalue中

cout << strvalue << " " << strothervalue << endl; // 123 124

nstate = ssio.rdstate(); // eofbit 0x01 已經讀取到最後了

cout << "stringstream state:" << nstate << endl;

ssio.clear(); // 清除eofbit狀態

nstate = ssio.rdstate(); // goodbit 0x00

cout << "stringstream state:" << nstate << endl;

strbuf = ssio.str(); // 從stringbuf中獲取內容

cout << "cleared state stringstream buffer:" << strbuf << endl; // 123 124

double lfvalue = 12.0123456789;

ssio << lfvalue; // 往stringstream中寫入double數值

strbuf = ssio.str(); // 從stringbuf中獲取內容

cout << "stringstream buffer:" << strbuf << endl; // 123 12412.0123456789

ssio >> strvalue;

cout << strvalue << endl;

ssio.str(""); // 設定stringstream中的buffer為空

strbuf = ssio.str(); // 從stringbuf中獲取內容

在使用stringstream流的時候需要注意,stringbuffer讀取到最後的時候會被設定eofbit標誌,可檢視c++ library了解細節便於出錯時快速的定位問題。通過stringstream流我們可以實現型別轉換,使用模組封裝型別的轉換過程可提高編寫**的效率。封裝是為了解決重複造輪子,我們有必要給自己造大量的輪子,以後就使用輪子組裝我們的車子。

通過模板封裝使得**更簡潔了,不過對於資料的一些控制就減弱,比如float型別的精度long型別的進製控制。這些需要通過更好的封裝方式才能達到,後續嘗試封裝下。

三、通過boost庫中的模板方法lexical_cast進行轉換

#include // 需要包含標頭檔案才能使用

lexical_cast和converttype封裝的形式有點像,其實是因為lexical_cast內部也是對於輸入輸出流的封裝。不過有大牛進行封裝了,我們就可以省去自己造輪子。

c 強制型別轉換 學習筆記

c 強制型別轉換分為四種,static cast,dynamic cast,const cast,reinterpret cast 一.為什麼在c 中還有特殊的四種強制轉換 二.static cast include iostream intmain 三.const cast include ios...

縱橫表轉換學習

動態橫表轉縱表 建表語句 if not object id class1 is null drop table class1 gocreate table class1 student nvarchar 2 數學 int,物理 int,英語 int,語文 int insert class1 sele...

位元組碼轉換學習

之前寫netty,雖然用的是nenty,實現了netty與protobuf的整合,不過現在看到的成熟的nenty開源專案,都是用netty4寫的,還是header和body,在handler中實現物件的轉換。學習netty的時候,關於位元組轉換,學習的記錄一下 第一 運算子 按位非 not 一元運算...