[問題] 有關 std::stringstream

看板C_and_CPP作者 (可愛小孩子)時間9年前 (2014/12/23 13:55), 編輯推噓7(7012)
留言19則, 10人參與, 最新討論串1/1
#include <iostream> #include <string> #include <sstream> using namespace std; int main(){ int a = 1, b = 2; string sa,sb; stringstream ss; ss << a; ss >> sa; ss << b; ss >> sb; cout << sa << endl; cout << sb << endl; // 問題:為什麼這邊印不出 2 // 如圖:http://codepad.org/11j38BHP return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 210.61.233.210 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1419314136.A.5BC.html

12/23 14:14, , 1F
因為 stringstream 沒有清空 在第17行加上 ss.clear()
12/23 14:14, 1F

12/23 14:14, , 2F
12/23 14:14, 2F

12/23 14:15, , 3F
去 Google 一下就可以查到 stringstream 的相關用法了
12/23 14:15, 3F

12/23 14:43, , 4F
謝謝 sos0214,原來 「設成空字串」跟 clear 要同時用
12/23 14:43, 4F

12/23 14:44, , 5F
才會有效,非常謝謝你
12/23 14:44, 5F

12/23 20:17, , 6F
clear 只清狀態旗標, 不清除字串
12/23 20:17, 6F

12/23 21:47, , 7F
這個雷以前踩過,只能說sstream清除非常不直覺...
12/23 21:47, 7F

12/23 21:48, , 8F
不過他也不大,所以直接在宣告一個來用也沒差....
12/23 21:48, 8F

12/24 03:27, , 9F
iostream大概是C++標準裡設計最糟糕的library了...
12/24 03:27, 9F

12/24 09:52, , 10F
所以大部分的建議都是, 不要重複使用這些東西...
12/24 09:52, 10F

12/24 10:56, , 11F
stream類都不要重用比較好 用scope的方式控制數量
12/24 10:56, 11F

12/24 10:56, , 12F
但是其實還是會有幾個像是fstream不重用不行的情況(死
12/24 10:56, 12F

12/25 00:06, , 13F

12/25 18:47, , 14F
iosteream新手初學的時候真是搞死我了
12/25 18:47, 14F

01/01 03:18, , 15F
其實也是有不用str("")的方式,舉個例子,像是input讀
01/01 03:18, 15F

01/01 03:19, , 16F
10個整數,中間卻夾雜了錯誤的字串,這時候就可以clear後
01/01 03:19, 16F

01/01 03:21, , 17F
特別再把不需要的字串拿掉就可以了
01/01 03:21, 17F

01/01 03:21, , 18F
用加總10個整數來當例子: http://goo.gl/JeVlCt
01/01 03:21, 18F

01/01 03:22, , 19F
PS: 要先compile 然後 sh testcase1.sh
01/01 03:22, 19F
文章代碼(AID): #1KcGFOMy (C_and_CPP)