(參閱:http://www.cppblog.com/sandywin/archive/2007/07/13/27984.html)
在寫程序的過程中,我們經常需要進行數據類型的轉換,也經常搞混。但是如果使用stringstream
的話,就在也不用擔心了。
sstream
stringstream
在頭文件<sstream>
中,<sstream>
庫定義了三種類:istringstream
、ostringstream
和stringstream
,分別用來進行流的輸入、輸出和輸入輸出操作。
使用stringstream
進行轉換,比C的<stdio.h>
的sprintf
等更安全,不用擔心輸錯格式化符號(如%d,%f等)也更方便。
直接轉換
最簡單的:
int n;
stringstream ss;
ss << s; //ss = "12345"
ss >> n; //n = 12345
或者string
轉char *
:
std::stringstream stream;
char result[8] ;
string s("8888");
stream << s; //向stream中插入8888
stream >> result; //抽取stream中的值到result
利用模板轉換
還可以利用模板,進行同一類轉換:
template<class T>
void to_string(string& result,const T& t)
{
ostringstream oss; //創建一個流
oss << t; //把值傳遞如流中
result = oss.str(); //獲取轉換後的字符轉並將其寫入result
}
然後就可以把基本數據類型都轉換爲string
了:
to_string(s, 1); //s = 1
to_string(s, 1.1); //s = 1.1
to_string(s, true); //s = 1
再通用一些,可以將輸入類型A和輸出類型B均用模板代替,會產生更普遍的轉換:
template<class out_type,class in_value>
out_type convert(const in_value& t)
{
stringstream stream;
out_type result; //這裏存儲轉換結果
stream << t; //向流中傳值
stream >> result; //向result中寫入值
return result;
}
進行A到B類型的轉換:
double d;
string salary;
string s2 = "12.56";
d = convert<double>(s2); //d = 12.56
salary = convert<string>(9000.0); //salary = "9000"
注意調用模板的時候要把返回值類型寫上。
關於重複使用的問題
首先有一個理念要搞清楚:無論是istringstream、ostringstream,還是stringstream,他們都是作爲臨時緩衝區存在的。
比如現在要寫一個文件:
ofstream ofile("output.txt");
要求每符合條件時,就往裏寫一行內容:
ofile << "blablabla" << endl;
這樣頻繁I/O會很影響效率。如果我們能夠把這些符合條件的東西先存起來,最後集中一次性寫入文件,一定會快不少。爲此,我們可以定義:
ofstream ofile("output.txt");
ostringstream oss;
每當符合條件時,我們先把符合條件的內容寫入緩存:
oss << "blablabla" << endl;
最後一次性寫入到文件:
ofile << oss.str();
則能大大提高效率。
所以說,這些緩衝區如果我們不手工清零的話,再次往裏放東西的時候他們會接着上次的內容往後添加。所以,如果我們要重複使用他們,一定要先清空。
當然,每次使用之前我們都直接新建一個也可以,但是,在多次轉換中重複使用同一個stringstream
(而不是每次都創建一個新的對象)對象最大的好處在於效率。stringstream
對象的構造和析構函數通常是非常耗費CPU時間的。
清空
注意對stringstream的清空使用的不是clear(),對clear()
的解釋如下:
void clear (iostate state = goodbit);
Set error state flags
Sets a new value for the stream’s internal error state flags.
它是設置標誌位的,不是用來清空內容的。
在stringstream
中,有函數str()
,它有兩種用法。
用法一:
string str() const;
returns a string object with a copy of the current contents of the stream.
它的作用是將stringstream
的內容以字符串的形式返回,比如上面在舉ostringstream
的例子的時候,我們最後寫回文件用的就是ofile << oss.str()
。
用法二:
void str (const string& s);
sets s as the contents of the stream, discarding any previous contents.
它的作用是將stringstream
原有的內容拋棄,並設置爲s。
所以我們對stringstream
的清空方式爲ss.str("")
,直接將其設置爲空串就好。