close
1. base on std C++11
編譯器為std C++11的,因為<string>中已經有包含了對應的轉換方法
標準庫中定義to_string(),可以將各種類型轉換成string類型
ex:
//int --> string
int
i = 5;
string s = to_string(i);
cout << s << endl;
//double --> string
double
d = 3.14;
cout << to_string(d) << endl;
//long --> string
long
l = 123234567;
cout << to_string(l) << endl;
//char --> string
char
c =
'a'
;
cout << to_string(c) << endl;
//自動轉換為int類型的參數
//char --> string
string cStr; cStr += c;
cout << cStr << endl;
另外亦提供stoi(),stol(),stof(),stod()做為將string轉為各種類型的資料
ex:
s =
"123.257"
;
//string --> int;
cout << stoi(s) << endl;
//string --> int
cout << stol(s) << endl;
//string --> float
cout << stof(s) << endl;
//string --> double
cout << stod(s) << endl;
2. before std C++11
stringStream:專門處理讀取或是寫入到string類別
標頭檔 #include <sstream>
a. int -> string
stringstream ss;
int number = 1;
//把int型態寫入stringstream
ss << number;
string convert_str;
ss >> convert_str; //透過串列運算子寫到string
b. string -> int (其他類別雷同)
stringstream ss;
string numberStr ="123";
int num;
ss << numberStr;
ss >> num;
清空stringsstream
stringstream ss;
處理辦法:
ss.str(""); (ss.str()是指stringstream內的字串)
ss.clear();
如果只寫其中一個的話
1.只使用str("")
使用str("")可以把先前的字串清空,但stringstream的串流已讀到尾端(eof)
如同讀檔,串流已到結尾,所以stringstream無法寫入
ex:
stringstream ss;
123,EOF ---------------> "",EOF
(經過ss.str(""))
2.只使用str.clear()
可繼續讀取string至stringstream,但原本資料依舊存在,但在寫入新資料時不會有什麼影響
ex:
stringstream ss;
123,EOF -------------->123,(繼續讀取)
(經過ss,clear())
假設接著寫入654
串流內為 123,654.EOF (紀錄從,這邊開始)
全站熱搜