user2252786
user2252786

Reputation: 1635

Reading space-separated numbers from file

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;
}

The problem is it works great in VS 2012, but in Dev C++ it just reads the first number in a file - the while loop goes only once. What is wrong?

It's supposed to work with .txt files. Number input should be like:

1 3 2 4 5

Upvotes: 0

Views: 2088

Answers (2)

juanchopanza
juanchopanza

Reputation: 227370

This is a more idiomatic way of reading integers from a file into a 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);
}

Upvotes: 4

Mats Petersson
Mats Petersson

Reputation: 129314

The code

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

will skip everything to the next newline. You probably don't want that in this case.

Upvotes: 2

Related Questions