Re: [問題] 將string轉成int輸出

看板C_and_CPP作者 (pziyout)時間11年前 (2012/09/09 12:41), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/3 (看更多)
※ 引述《ghayen (給10班全體:教練感謝你們)》之銘言: : 開發平台(Platform): (Ex: VC++, GCC, Linux, ...) : C++ : 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) : STL : 問題(Question): : 小弟我想將IP Address (type std::string )轉換成int型態,寫了一個小程式進行測試。 : 主要的問題是轉換過的ip值,只會顯示第一個值,而不是完整的ip。 : 已知道應該是int不適用,想請問板上各位C++先進我應該用哪種型態表示比較適合? : 懇請賜教,謝謝。 標準的輸出入題目: #include <sstream> istringstream istr("140.115.100.200") ; char ch ; int n ; while ( istr ) { if ( istr >> n ) { cout << n ; } else { istr.clear() ; if ( istr >> ch ) { cout << ch ; } else { break ; } } } cout << endl ; 或者寫好玩的: istringstream istr("140.115.100.200") ; string ip ; vector<int> ips ; while ( getline(istr,ip,'.') ) ips.push_back(str2int(ip)) ; copy(ips.begin(),ips.end()-1,ostream_iterator<int>(cout,".")) ; cout << ips.back() << endl ; int str2int( const string& foo ) { istringstream istr(foo) ; int n ; istr >> n ; return n ; } 以上需要 #include <vector> #include <iterator> #include <algorithm> #include <string> -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.115.25.21
文章代碼(AID): #1GJ1u15M (C_and_CPP)
文章代碼(AID): #1GJ1u15M (C_and_CPP)