无法将文件读入矢量

时间:2013-03-29 14:30:38

标签: c++

我有一个三行有三个整数的文件。它看起来像这样:

  

000
  001
  010

我正在尝试将每个整数读入向量位置,但我不知道我是否正确行事。这是我的代码:

#include <fstream>
#include <iterator>
#include <vector>

int main()
{
   std::vector<int> numbers;
   std::fstream out("out.txt");

   std::copy(std::ostreambuf_iterator<int>(out.rdbuf()),
             std::ostreambuf_iterator<int>(), std::back_inserter(numbers));
}

我在这里做错了什么?我在复制的行上收到“无匹配函数调用”错误。

2 个答案:

答案 0 :(得分:5)

你使用了错误的迭代器。

您需要istreambuf_iterator,而不是ostreambuf_iterator

 std::copy(std::istreambuf_iterator<int>(out.rdbuf()),
           std::istreambuf_iterator<int>(), std::back_inserter(numbers));

请注意ostreambuf_iterator是输出迭代器。它用于,而不是。你想要做的是阅读,你需要istreambuf_iterator

但是等等!上面的代码也不起作用,为什么?

因为您正在使用istreambuf_iterator并将int传递给它。 istreambuf_iterator将数据读取为{em>无格式缓冲区,类型为char*wchar_t*istreambuf_iterator的模板参数可以是charwchar_t

您实际需要的是istream_iterator,它读取给定类型的格式化数据:

std::copy(std::istream_iterator<int>(out), //changed here also!
          std::istream_iterator<int>(), std::back_inserter(numbers));

现在效果很好。

请注意,您可以避免使用std::copy,并使用std::vector本身的构造函数作为:

std::fstream in("out.txt");

std::vector<int> numbers((std::istream_iterator<int>(in)), //extra braces
                         std::istream_iterator<int>());

注意第一个参数附加的大括号,用于避免C +++中的 vexing parse

如果已经创建了矢量对象(并且可选地它中包含一些元素),那么您仍然避免std::copy

numbers.insert(numbers.end(), 
               std::istream_iterator<int>(in), //no extra braces
               std::istream_iterator<int>());

在这种情况下不需要额外的括号。

希望有所帮助。

答案 1 :(得分:0)

通过Dietal&amp;阅读“C ++如何编程”一书。 Dietal,关于向量的章节。我向你保证,你所有的问题都将得到解决。您已打开输出的文本文件而不是输入。我建议你不要使用这个函数,而是应该读入字符串并使用迭代器将它们复制到向量中,直到在文件中遇到EOF。编辑:如果您是Vector的新手,这种方式更自然,易于阅读和理解。

相关问题