Splitting the string using boost::algorithm::split

2019-02-16 03:08发布

问题:

i have the following code.

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;
   }
  }
 }
}

This is the Output i am getting.

Connect
10.172.21.121
10.109.12.122

I need to store 10.172.21.121 in ip1 & 10.109.12.122 in ip2. How do i do that

Thanks

回答1:

If you are already using boost, why not store IP addresses in objects of appropriate class?

#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';
}

If you have to convert them to integers, you can do so when necessary, with to_bytes for example.



标签: c++ boost