c++ - 从文件中读取空格分隔的数字

标签 c++

std::vector<int> loadNumbersFromFile(std::string name)
{
    std::vector<int> numbers;

    std::ifstream file;
    file.open(name.c_str());
    if(!file) {
        exit(EXIT_FAILURE);
    }

    int current;
    while(file >> current) {
        numbers.push_back(current);
        file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    return numbers;
}

问题是它在 VS 2012 中运行良好,但在 Dev C++ 中它只读取文件中的第一个数字——while 循环只运行一次。怎么了?

它应该与 .txt 文件一起使用。数字输入应该是这样的:

1 3 2 4 5

最佳答案

这是一种更惯用的从文件中读取整数到 vector 中的方法:

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

std::vector<int> loadNumbersFromFile(const std::string& name)
{
  std::ifstream is(name.c_str());
  std::istream_iterator<int> start(is), end;
  return std::vector<int>(start, end);
}

关于c++ - 从文件中读取空格分隔的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16718010/

相关文章:

c++ - 使用 int 的 priority_queue 和自定义比较

c++ - 菜单项是单选样式,而不是MF_CHECKED?

c++ - 在函数中传递的指针的内存位置被删除

c++ - 如何更改 qt 4.3 中 Q3Table 的垂直标题列的宽度?

c++ - 调用基方法模板子类

c++ - 尝试使用 boost 库时缺少 gmp.h

c++ - 蓝图不会影响其父级 - 虚幻引擎

c++ - 我可以在运行时绑定(bind)数据类型吗?

C++ strict-aliasing agnostic cast

c++ - C++ 中 const 指针可变