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

看板C_and_CPP作者 (pziyout)時間7年前 (2017/06/20 16:02), 編輯推噓0(001)
留言1則, 1人參與, 最新討論串2/4 (看更多)
※ 引述《a855341 (崧樓下的腳印)》之銘言: : 開發平台(Platform): Win7 : 編譯器(Ex: GCC, clang, VC++...):DevC : 問題(Question): : 新手上路遇到一個問題 : 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), 來自: 140.115.25.29 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1497945727.A.6C0.html

06/21 11:25, , 1F
感謝P大解釋方法 我晚點才有電腦來試試看
06/21 11:25, 1F
文章代碼(AID): #1PIDP_R0 (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1PIDP_R0 (C_and_CPP)