从C ++中的文件中读取IP地址

时间:2013-11-21 18:57:24

标签: c++ file-io

我试图从文本文件中读取几千个IPv4地址并将它们放入C ++字符串数组中。这是我到目前为止所拥有的

#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;

}

当我运行这个时,我得到一个未处理的异常,我不确定是什么问题。我主要使用Java而不是很多C ++,所以如果我错过了一些明显的东西,我会道歉。

2 个答案:

答案 0 :(得分:5)

你的数组可能超出范围。

尝试:

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

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

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

编辑:正如Dave Rager所指出的,迭代的最大值应该是i而不是10000。

答案 1 :(得分: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标准