3

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?

1 Answers1

6

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
康桓瑋
  • 33,481
  • 5
  • 40
  • 90