如果您可以使用标准容器和算法,则以下解决方案会将所有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标准版
有一件事: se z <10000,否则您将读取超出数组结尾。索引是基于零的。目前您的z <= 10000 – mathematician1975
您的文件中是否包含10000个元素?如果不是,则将'for'循环中的条件更改为'z