从文件读取空格分隔的数字 [英] Reading space-separated numbers from file
本文介绍了从文件读取空格分隔的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
std :: vector< int> loadNumbersFromFile(std :: string name)
{
std :: vector< int>数字;
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(),'\\\
');
}
返回数字;问题是它在VS 2012中工作得很好,但是在Dev C ++中,它只是一个简单的例子。读取文件中的第一个数字 - while循环只进行一次。什么是错误?
它应该与.txt文件一起使用。数字输入应为:
1 3 2 4 5
解决方案这是一种从文件中读取整数到向量的更惯用的方法:
#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);
}
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);
}
这篇关于从文件读取空格分隔的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文