Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::views::istream with std::views::take

I compiled the following code with g++ 12.2.1:

#include <iostream>
#include <ranges>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
    std::vector<int> vi;
    std::ranges::copy(std::views::istream<int>(std::cin) | std::views::take(3), std::back_inserter(vi));
    for (auto i : vi)
        std::cout << i << ' ';
}

Input:

1 2 3
4

Output: 1 2 3

Why do I have to enter 4 numbers instead of 3 and discard the last one? How to solve?

like image 708
Blackteahamburger Avatar asked Jan 28 '26 09:01

Blackteahamburger


1 Answers

When you finish typing 1 2 3, views::istream<int>(std::cin) | views::take(3) did not reach the end, because its iterator just points to the last element and doesn't pass the end.

You can use CTRL+D (for linux) or CTRL+Z (for Windows) to terminate the input like

1 2 3
Ctrl + D
like image 97
康桓瑋 Avatar answered Jan 29 '26 23:01

康桓瑋



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!