从文本文件C ++中提取IP

时间:2015-03-14 01:21:23

标签: c++11

我是 C++ 的新程序员,我想创建一个从文本文件中提取IP的代码 我试图将txt文件转换为Vector(字符串)以便于过滤,但我无法获得所有的内容,例如XXX.XXX.XXX.XXX

3 个答案:

答案 0 :(得分:0)

    #include<iostream>
#include<fstream>

using namespace std;

int main() {

 ifstream myReadFile;
 myReadFile.open("text.txt");
 char output[100];
 if (myReadFile.is_open()) {
 while (!myReadFile.eof()) {


    myReadFile >> output;
    cout<<output;


 }
}
myReadFile.close();
return 0;
}

如果文本文件每行只包含IP,请使用此项。

或者取决于您使用的c ++:

    std::ifstream file("Read.txt");
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
  file_contents += str;
  file_contents.push_back('\n');
}  

答案 1 :(得分:0)

鉴于ip可以嵌入到某些文本中,我们将解析字符串并获取它。

#include <iostream>
#include <string>
#include <iterator>
#include <vector>
#include <sstream>
using namespace std;

string ip(string str)
{
    //middle portion
    auto firstDot = str.find_first_of('.');
    auto lastDot = str.find_last_of('.');
    int dotCount = 0;

    for(auto i = firstDot; i <= lastDot; i++)
    {
        if(!isdigit(str.at(i)) && str.at(i) != '.') //e.g 127.ss.0y.1
            return string("");
        if(str.at(i) == '.')
            dotCount++;
    }
    if(dotCount != 3)   //eg. 127.0.1 (not sure if this is wrong though)
        return string("");

    string result = str.substr(firstDot,lastDot-firstDot + 1);

    //left portion 

    size_t x = 0; //number consegative digits from the first dot

    for(auto i = firstDot-1; i >= 0; i--)
    {
        if(!isdigit(str.at(i)))
            break;
        else if(x == 3) //take first 3
            break;
        x++;
    }
    if(x == 0)
        return string("");

    result.insert(0,str.substr(firstDot-x,x));

    //right portion
    size_t y = 0;
    for(auto i = lastDot + 1; i < str.length(); i++)
    {
        if(isdigit(str.at(i)))
        {
            if(y == 3)
                break;
            result.push_back(str.at(i));
            y++;
        }
        else
            break;
    }
    if(y == 0)
        result.push_back('0');
    return result;
}
int main()
{
    string test = "1111127.0.0.11111 xx23.45.12.# xxxx.34.0.13 124.sd.2.1 sd.45.56.1";
    string x,y;
    vector<string> ips;

    stringstream stream;
    stream<<test;

    while(stream>>x)
        if(!(y = ip(x)).empty())
            ips.push_back(y);
    for(auto z : ips)
        cout<<z<<"\t";

    cout<<endl;
    system("pause");
    return 0;
}

答案 2 :(得分:0)

我是C ++ 11的新手。我为你做了以下简单的例子。它基于正则表达式库。希望它适合你!

#include <iostream>
#include <string>
#include <regex>

int main ()
{
    std::string s ("There's no place like 127.0.0.1\n");
    std::smatch m;
    std::regex e ("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");

    while (std::regex_search (s,m,e)) {
        for (auto x:m) std::cout << x << " ";
        std::cout << std::endl;
        s = m.suffix().str();
    }

    return 0;
}