Re: [問題] 將string轉成int輸出
※ 引述《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
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 3 篇):