简体   繁体   English

istream_iterator初始化向量

[英]istream_iterator to initialize vector

I'm trying to read from a ifstream fin and put it into a vector vec1 using istream_iterators. 我正在尝试从ifstream 鳍中读取内容,并使用istream_iterators将其放入向量vec1中。 I've seen these things all over the place: 我到处都看过这些东西:

vector<int> vec1((istream_iterator<int>(fin)),istream_iterator<int>);

I want to keep the istream_iterators for later use, so I thought "This should work": 我想保留istream_iterators供以后使用,所以我认为“这应该可以工作”:

istream_iterator<int> iit(fin);
istream_iterator<int> eos;
vector<int> vec1(iit,eos);

... It doesn't work =( my vector is completly empty. (the file i read from is a txt-file with nothing but digits). ...这是行不通的=(我的向量完全是空的。(我读取的文件是一个txt文件,除了数字外什么都没有)。

EDIT: The txt looks as follows: 编辑: txt如下所示:

06351784798452318596415234561
6641321856006

As per comment, the first sequence of digits is greater than the maximum value for an int so the input operation will fail resulting in the vector remaining empty. 根据注释,第一个数字序列大于int的最大值,因此输入操作将失败,从而导致vector保持为空。

You can obtain the maximum values for int , etc using the std::numeric_limits template: 您可以使用std::numeric_limits模板获取int等的最大值:

std::cout << std::numeric_limits<int>::max() << "\n";

As an intermediate step you might want to try iterating over the sequence immediately to see if there is something (probably not): 作为中间步骤,您可能想要立即遍历该序列以查看是否有东西(可能没有):

while (iit != eos) {
    std::cout << *iit++ << '\n';
}

If this doesn't print anything check that your stream is in good shape initially: 如果仍然无法打印任何内容,请先检查您的信息流是否处于良好状态:

if (!fin) {
    std::cout << "file not opened!\n";
}

If the stream only contaibs digits and no spaces it probably overflows and reading an int just fails as a result. 如果流仅包含数字且没有空格,则它很可能会溢出,因此读取int失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM