0
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
4

2 回答 2

4

这是将整数从文件读取到向量中的更惯用的方式:

#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);
}
于 2013-05-23T15:34:47.167 回答
2

编码

file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

将跳过所有内容到下一个换行符。在这种情况下,您可能不希望这样。

于 2013-05-23T15:34:19.010 回答