我如何读取每行都是单个数字的文件,然后将该数字输出到行向量中?
例如:file.txt 包含:
314
159
265
123
456
我已经尝试过这个实现:
vector<int> ifstream_lines(ifstream& fs) {
vector<int> out;
int temp;
getline(fs,temp);
while (!fs.eof()) {
out.push_back(temp);
getline(fs,temp);
}
fs.seekg(0,ios::beg);
fs.clear();
return out;
}
但是当我尝试编译时,我收到如下错误:
error C2784: 'std::basic_istream<_Elem,_Traits> &std::getline
(std::basic_istream<_Elem,_Traits> &,std::basic_string<_Elem,_Traits,_Alloc> &)' :
could not deduce template argument for 'std::basic_istream<_Elem,_Traits> &' from 'std::ifstream'
所以,显然,有些事情是错误的。有没有比我正在尝试的更优雅的解决方案? (假设像 Boost 这样的第三方库不可用)
谢谢!
我怀疑你想要这样的东西:
#include <vector>
#include <fstream>
#include <iterator>
std::vector<int> out;
std::ifstream fs("file.txt");
std::copy(
std::istream_iterator<int>(fs),
std::istream_iterator<int>(),
std::back_inserter(out));
“Tim Sylvester”描述的标准迭代器是最好的答案。但我不会使用
std::copy()
,而是使用采用迭代器的 vector<>
构造函数。
std::ifstream fs("file.txt");
std::vector<int> out{std::istream_iterator<int>{fs}, std::istream_iterator<int>{}};
但是如果你想要手动循环,
只是提供一个反例:'jamuraa'
vector<int> ifstream_lines(ifstream& fs)
{
vector<int> out;
int temp;
while(fs >> temp)
{
// Loop only entered if the fs >> temp succeeded.
// That means when you hit eof the loop is not entered.
//
// Why this works:
// The result of the >> is an 'ifstream'. When an 'ifstream'
// is used in a boolean context it is converted into a type
// that is usable in a bool context by calling good() and returning
// somthing that is equivalent to true if it works or somthing that
// is equivalent to false if it fails.
//
out.push_back(temp);
}
return out;
}
std::getline(stream, var)
读入 std::string
表示 var
。 我建议使用流运算符来读取 int
,并在需要时检查错误:
vector<int> ifstream_lines(ifstream& fs) {
vector<int> out;
int temp;
while (!(fs >> temp).fail()) {
out.push_back(temp);
}
fs.seekg(0,ios::beg);
fs.clear();
return out;
}