如何解析IP字符串 [英] How to parse ip string

查看:127
本文介绍了如何解析IP字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原谅我,我是C ++场景的新手,我尝试制作程序时用户可以在其中输入ip到批处理文件中,以便在我输入和ip之类的172.19.Etc时仍能找到有效端口,我只能得到172

Forgive Me I''m New To The C++ Scene Im Trying To Make A Program Were The User Can Enter There Ip Into Batch File To Look For Alive Ports Anyways When I Enter And Ip Like 172.19.Etc I Only Get 172

string ip;
	int anwswer;
	int price=0;
  cout << "Enter IPv4: ";
  getline (cin,ip);
  stringstream(ip) >> price;
  cout << price <<"\n" <<"Is this right? \n";
  cin>>i;
  
  {
	int if(i == "y";

	  cout<<"DONE!"; //place in to batch file
	  else NULL; //goto main
  }
 
  system("pause");
  return 0;

推荐答案

这是stringstream提取运算符的正确行为:您请求了int,并且它提供了string中表示的第一个有效int.
如果要将四个IP八进制提取为整数,请尝试以下代码:
That''s the correct behaviour of the stringstream''s extraction operator: you requested an int and it provided the first valid int represented in the string.
If you want to extract the four ip octects as integers then try the following code:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
  string ip;
  int anwswer;
  int octet[4];
  char c;

  do
  {
    cout << "Enter IPv4: ";
    getline (cin,ip);
    stringstream s(ip);
    for (int n=0; n<4; ++n)
      s >> octet[n] >> c;

    for (int n=0; n<4; ++n)
      cout << "octet[" << n << "]=" << octet[n] << endl;

    cin>>c;
    if(c == 'y')
      cout<<"DONE!"; //place in to batch file
    else
      cout<<"NOT DONE!"; /
  } while (c != 'y');

  return 0;
}


替换...

Replace ...

stringstream(ip) >> price;
cout << price <<"\n" <<"Is this right? \n";



...与...



... with ...

in_addr_t ip = inet_addr(ip.c_str());
cout << inet_ntoa(ip) <<"\n" <<"Is this right? \n";


这篇关于如何解析IP字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆