如何从文件读取整数到C++中的整数数组?因此,例如,该文件的内容:从文件中逐行读取整数
23
31
41
23
将成为:
int *arr = {23, 31, 41, 23};
?
我其实有两个问题。首先,我不知道我该如何逐行读取它们。对于一个整数来说,这将非常容易,只要file_handler >> number
语法就可以做到这一点。我如何一行一行地做这件事?
第二个问题似乎更难以克服的是我应该如何为这个东西分配内存? :U
如何从文件读取整数到C++中的整数数组?因此,例如,该文件的内容:从文件中逐行读取整数
23
31
41
23
将成为:
int *arr = {23, 31, 41, 23};
?
我其实有两个问题。首先,我不知道我该如何逐行读取它们。对于一个整数来说,这将非常容易,只要file_handler >> number
语法就可以做到这一点。我如何一行一行地做这件事?
第二个问题似乎更难以克服的是我应该如何为这个东西分配内存? :U
std::ifstream file_handler(file_name);
// use a std::vector to store your items. It handles memory allocation automatically.
std::vector<int> arr;
int number;
while (file_handler>>number) {
arr.push_back(number);
// ignore anything else on the line
file_handler.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
呃,载体......我不得不通过参数来传递这一个到另一个功能 - 是这好吗?我听说它很慢。 – user2252786 2013-04-20 17:17:10
@ user2252786:如果你传递一个引用,它不会很慢。反正它可能并不那么慢。 – 2013-04-20 17:17:42
@ user2252786:这并不慢。不要听你所听到的一切(除了它在这里)。 – 2013-04-20 17:24:41
您只需使用file >> number
即可。它只知道如何处理空格和换行符。
对于可变长度阵列,请考虑使用std::vector
。
此代码将使用文件中的所有数字填充矢量。
int number;
vector<int> numbers;
while (file >> number)
numbers.push_back(number);
下面是做这件事:
#include <fstream>
#include <iostream>
#include <iterator>
int main()
{
std::ifstream file("c:\\temp\\testinput.txt");
std::vector<int> list;
std::istream_iterator<int> eos, it(file);
std::copy(it, eos, std::back_inserter(list));
std::for_each(std::begin(list), std::end(list), [](int i)
{
std::cout << "val: " << i << "\n";
});
system("PAUSE");
return 0;
}
你也可以使用std :: copy来打印:'std :: copy(list.begin(),list.end(),std :: ostream_iterator
是的,但我只限于分隔符,为了输出的清晰度,我想放置“val:”前缀。 – 2013-04-20 18:05:20
不使用阵列中使用向量。
#include <vector>
#include <iterator>
#include <fstream>
int main()
{
std::ifstream file("FileName");
std::vector<int> arr(std::istream_iterator<int>(file),
(std::istream_iterator<int>()));
// ^^^ Note extra paren needed here.
}
使用std ::矢量而非阵列和新的push_back整数,向量将增长分配内存自动 – piokuc 2013-04-20 17:15:52