# stringstream ## **1. 什麼是 `stringstream`?** `stringstream` 是 `C++` 標準函式庫 `<sstream>` 提供的一種字串流類別,可用來處理字串與數據的輸入、輸出、轉換等功能。 - **主要功能**: - **將數值轉換為字串** - **從字串提取數值** - **拼接與處理字串** 超強大的字串處理功能,用過的都說讚!! ## **2. `stringstream` 的語法** 要使用 `stringstream`,需包含 `<sstream>` 標頭檔: ```cpp= #include <iostream> #include <sstream> using namespace std; ``` ### **(1) 數值轉字串** ```cpp= #include <iostream> #include <sstream> using namespace std; int main() { int number = 100; stringstream ss; ss << number; // 將數字輸入字串流 string str = ss.str(); // 轉換為字串 cout << "數字轉字串: " << str << endl; return 0; } ``` **輸出:** ``` 數字轉字串: 100 ``` ### **(2) 字串轉數值** ```cpp= #include <iostream> #include <sstream> using namespace std; int main() { string str = "250"; stringstream ss(str); //初始化ss為str int number; ss >> number; // 塞入數值 cout << "字串轉數字: " << number + 50 << endl; return 0; } ``` **輸出:** ``` 字串轉數字: 300 ``` ### **分割字串** `stringstream` 可用來拆解字串。 遇到要用 `getline` 輸入一長串字串並要做字串處理的討厭題目時,他就可以節省很多迴圈和判斷的使用了。(我以前還不知道這功能時,遇到這種題目都快哭了)。 ```cpp= #include <iostream> #include <sstream> using namespace std; int main() { string text = "apple orange banana"; stringstream ss(text); string word; while (ss >> word) { // 逐個讀取單字 cout << word << endl; } return 0; } ``` **輸出:** ``` apple orange banana ``` ### **拼接字串** ```cpp #include <iostream> #include <sstream> using namespace std; int main() { stringstream ss; ss << "Hello " << "World! " << 2024; cout << ss.str() << endl; return 0; } ``` **輸出:** ``` Hello World! 2024 ``` ## **3. `stringstream` 進階應用** ### **(1) 清除 `stringstream`** 如果要重複使用 `stringstream`,需清空內容: ```cpp ss.str(""); // 清空字串內容 ss.clear(); // 重置錯誤標誌 ``` 這樣他就跟全新的一樣囉!! ### **(2) 讀取多個數值** ```cpp= #include <iostream> #include <sstream> using namespace std; int main() { string str = "10 20 30 40 50"; stringstream ss(str); int num; while (ss >> num) { cout << num * 2 << " "; } return 0; } ``` **輸出:** ``` 20 40 60 80 100 ``` ## 預告 輸入的細節部分會在下一章,並且與 `getline` 的補充功能一同講解喔!!!
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up