2013-11-21 27 views
0

我正在尝试从文本文件读取几千个IPv4地址,并将它们放入C++字符串数组中。以下是我迄今为止从C++中的文件读取IP地址

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

int main() 
{ 
    string fileName1,fileName2; 
    fileName1="file1Large.txt"; 
    ifstream inData; 
    inData.open(fileName1); 
    string file1[10000]; 
    int i=0; 
    while(inData) 
    { 
     inData>>file1[i]; 
     i++; 
    } 
    cout<<"File1: "<<endl; 
    for(int z=0; z <= 10000; z++) 
    { 
     cout<<file1[z]; 
    } 
    inData.close(); 
    system("pause"); 
    return 0; 

} 

当我运行此我得到一个未处理的异常,我不知道什么是wrong.I已大多采用的Java并没有太多的C++,所以我很抱歉,如果我缺少明显的东西。

+0

有一件事: se z <10000,否则您将读取超出数组结尾。索引是基于零的。目前您的z <= 10000 – mathematician1975

+1

您的文件中是否包含10000个元素?如果不是,则将'for'循环中的条件更改为'z

回答

5

您的数组可能会超出范围。

尝试:

while(i < 10000 && inData >> file1[i]) 
    { 
     i++; 
    } 

此外,这肯定是一个问题:

for(int z=0; z < i; z++) // remove = and change 10000 to i 
    { 
     cout<<file1[z]; 
    } 

编辑:戴维狂怒指出,迭代的最大价值应该是我,而不是10000

2

如果您可以使用标准容器和算法,则以下解决方案会将所有IP读取到一个字符串向量中(假设该输入由换行分隔):

#include<iostream> 
#include<fstream> 
#include<algorithm> 
#include<string> 
#include<vector> 
#include<iterator> 
// 
// compile as: 
// 
// g++ example.cpp -std=c++11 -Wall -Wextra 
// 
// I used GCC 4.8.1 on OS X 10.7.4 
// 
int main() { 
    // this container will grow automatically; it saves you the hassle 
    // of managing the underlying buffer 
    std::vector<std::string> data; 

    { // this is a new scope for the file stream; it will close 
    // automatically when it leaves this scope (you don't have to call 
    // fp.close()) 
    std::ifstream fp("ips.txt"); 
    // this will do literally as it says: "for as long as you can 
    // extract an string from the file, back-insert it into the vector 
    // of strings called 'data'" 
    std::copy(std::istream_iterator<std::string>(fp), 
       std::istream_iterator<std::string>(), 
       std::back_inserter<std::vector<std::string>>(data)); 
    } // this is the end of the scope mentioned above; `fp` does not 
    // exist beyond here 

    // this simply prints the data as you read it; it says "copy all the 
    // contents of data to the output stream called "cout" separating 
    // every entry with a new line" 
    std::copy(data.begin(), 
      data.end(), 
      std::ostream_iterator<std::string>(std::cout, "\n")); 
} 

示例文件:

$ cat > ips.txt 
1.2.3.4 
5.6.7.8 
9.10.11.12 

样品运行:

$ ./a.out 
1.2.3.4 
5.6.7.8 
9.10.11.12 

通知我存在于该使用标准容器和算法例如,您的编译器需要支持C++ 11标准版