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
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);
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.