2015-03-14 4 views
-2

Im новый программист в C++ и я хочу, создающих код, извлечь IP из текстовых файлов Я попытался преобразовать текстовый файл в Вектор (строка) будет легко фильтрации, но я не могу получить все FORMES как XXX.XXX.XXX.XXXИзвлечение IP из текстового файла C++

ответ

0

Учитывая, что ф может быть вложена в какой-то текст, мы будем разбирать строку и извлечь его.

#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; 
} 
+0

спасибо большое;) #jafar –

+0

, но если у меня есть строка, что это containe "àç10.12.1.1 \" ??? –

+0

@ MED-ELOMARI Я обновил ответ. –

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'); 
} 
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; 
} 
+0

строка 12: синтаксическая ошибка: missing ',' before ':' Я не понял значение «regex» , что он должен делать? и спасибо за ответ (y) –

Смежные вопросы