Re: [問題] 如何把字串中的數字取出(有空格相間)

看板C_and_CPP作者 (我正在想要換什麼)時間7年前 (2017/06/20 23:13), 編輯推噓2(207)
留言9則, 4人參與, 最新討論串3/4 (看更多)
C++ 其實提供非常多高階函式把單調的迴圈操作包裝起來 以這個例子來說,切割字串可以用 istringstream 沒錯 但還可以搭配 istream_iterator 把資料流 (stream) 轉成 iterator 有了 iterator 就可以搭配所有 STL 泛型函式使用 比如說把字串切割後存進 vector: istringstream input("1 22 333 44 5"); istream_iterator<int> begin(input); istream_iterator<int> end; vector<int> data; data.insert(data.begin(), begin, end); 又,C++ 提供 std::accumulate,讓你可以把 iterator 尋訪過的每個元素加起來 這樣就完全不需要另一個 vector 來存這些數字: istringstream input("1 22 333 44 5"); istream_iterator<int> begin(input); istream_iterator<int> end; cout << accumulate(begin, end, 0) << endl; // 405 只要把資料用 iterator 表示,就可以利用 STL 內大量的泛型函式 而且執行速度非常快。 ※ 引述《pziyout (pziyout)》之銘言: : : python可以把一串字串(或輸入一大段字串用空白或逗號相間),轉換後運算 : : 例如 " 10 20 30 123 " 變成-->" '10','20','30','123' "之類的,對數字進行運算 : : (利用 .split() + .append() 之類的~) : : 但想請問C 或C++該如何進行? : 使用 istringstream 與 vector : #include <iostream> : #include <sstream> : #include <vector> : using namespace std ; : int main() { : int i , n , s ; : string foo = " 23 11 34 98 " ; : istringstream istr(foo) ; : vector<int> nums ; : while ( istr >> n ) nums.push_back(n) ; : cout << ( s = nums[0] ) ; : for ( i = 1 ; i < nums.size() ; ++i ) { : s += nums[i] ; : cout << " + " << nums[i] ; : } : cout << " = " << s << endl ; : return 0 ; : } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 153.156.42.69 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1497971604.A.D82.html

06/21 11:26, , 1F
感謝L大解釋方法 我晚點才有電腦來試試看
06/21 11:26, 1F

06/21 11:26, , 2F
但有些東西開始看不懂了QAQ 新手上路 但還是非常感謝
06/21 11:26, 2F

06/23 03:45, , 3F
這作法太逆天 上次在 stackoverflow 看到整個人都高潮了
06/23 03:45, 3F

06/24 16:12, , 4F
這其實算很標準做法 沒啥好逆天的,誰叫std::string
06/24 16:12, 4F

06/24 16:12, , 5F
連.split()這種東西都不提供 XD
06/24 16:12, 5F

06/24 16:13, , 6F
你去查how to split a string c++大概都會找到這方法
06/24 16:13, 6F

07/01 16:07, , 7F
Standard library 應該要有split才對 最好Python 的全
07/01 16:07, 7F

07/01 16:07, , 8F
都抄來xD
07/01 16:07, 8F

07/01 16:08, , 9F
覺得很多部分標準實在進展太慢
07/01 16:08, 9F
文章代碼(AID): #1PIJkKs2 (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1PIJkKs2 (C_and_CPP)