2010-11-19 66 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例如。