比如输入是192.168.80.12-15,解析成192.168.80.12、192.168.80.13、192.168.80.14、192.168.80.15。
1 #include <iostream> 2 #include <vector> 3 #include <string> 4 #include <sstream> 5 #include <fstream> 6 7 void ReadDataFromFile(std::string &filename, std::vector<std::string> &lines_feat) { 8 std::ifstream vm_info(filename.c_str()); 9 std::string lines; 10 11 lines_feat.clear(); 12 13 while(!vm_info.eof()) { 14 getline(vm_info, lines); 15 if(lines.empty()) 16 break; 17 18 lines_feat.push_back(lines); 19 } 20 } 21 22 std::vector<std::string> split(const std::string& s, char delimiter) { 23 std::vector<std::string> tokens; 24 std::string token; 25 std::istringstream tokenStream(s); 26 27 while(std::getline(tokenStream, token, delimiter)) { 28 tokens.push_back(token); 29 } 30 return tokens; 31 } 32 33 int stringtoint(const std::string& s) { 34 std::istringstream iss(s); 35 36 int num; 37 38 return iss>>num?num:0; 39 } 40 41 void printip(const std::string& s) { 42 std::vector<std::string> temp, ip_segment; 43 44 temp=split(s, '-'); 45 ip_segment=split(temp.front(), '.'); 46 47 std::string ip_start=ip_segment.back(), ip_end=temp.back(); 48 int start, end; 49 start=stringtoint(ip_start); 50 end=stringtoint(ip_end); 51 52 for(size_t i=start;i<=end;++i) { 53 std::cout<<ip_segment[0]<<"."<<ip_segment[1]<<"."<<ip_segment[2]<<"."<<i<<"\n"; 54 } 55 56 } 57 58 int main() { 59 std::string file_path("vm.data"); 60 std::vector<std::string> ip_vec; 61 62 ReadDataFromFile(file_path, ip_vec); 63 for(std::vector<std::string>::const_iterator it=ip_vec.begin();it!=ip_vec.end();++it) { 64 printip(*it); 65 } 66 67 return 0; 68 }