2010-11-19 231 views
0

我有以下代碼。使用boost :: algorithm :: split分割字符串

using namespace std; 
using namespace boost; 
int main() 
{ 
SystemConnect hndl; 
int ip1[15],ip2[15]; 
string line; 
while (cout<<"LP>" && getline(cin,line)) { 
    if (line=="exit") 
    break; 
    if (line=="Connect 10.172.21.121 10.109.12.122"){ 
    string str; 
     str="ConInit 10.172.21.121 10.109.12.122"; 
    vector<string> results; 
    split(results,str,is_any_of(" ")); 
    for(vector<string>::const_iterator p=results.begin();p!=results.end();p++){ 
    cout<<*p<<endl; 
    } 
    } 
} 
} 

這是我得到的輸出。

Connect 
10.172.21.121 
10.109.12.122 

我需要在IP1 & 10.109.12.122存儲10.172.21.121的IP2。我如何做到這一點

感謝

+0

爲什麼ip1和ip2定義爲int []?您希望他們以何種形式存儲IP地址? – 2010-11-19 12:33:11

+2

爲什麼你認爲你需要一個15元素的int數組來存儲IP地址? – 2010-11-19 12:35:36

回答

23

如果您已經使用升壓,爲什麼不是IP地址在適當的類的對象存儲?

#include <iostream> 
#include <vector> 
#include <string> 
#include <boost/algorithm/string.hpp> 
#include <boost/asio.hpp> 
namespace ip = boost::asio::ip; 
int main() 
{ 
    std::string str = "ConInit 10.172.21.121 10.109.12.122"; 
    std::vector<std::string> results; 
    boost::split(results, str, boost::is_any_of(" ")); 
    ip::address ip1 = ip::address::from_string(results[1]); 
    ip::address ip2 = ip::address::from_string(results[2]); 
    std::cout << " ip1 = " << ip1 << " ip2 = " << ip2 << '\n'; 
} 

如果你必須將它們轉換爲整數,你可以這樣做,必要時配合to_bytes例如。