When I was writing this answer, I was trying to scan a space-separated input string and store it in a vector. A user suggested the use of std::back_inserter
and std::copy()
to accept the input, over usage of std::istringstream
:
std::copy(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(), std::back_inserter(vec));
This seems fine (and works fine too!). But, when I copy-pasted the code into Visual Studio, it breaks only on non-number input, i.e. something like:
3 2 1 4<space/no-space>k
Is this a bug in MVCC?
I am using MVCC v14.27 (142) with Visual Studio 2019 (16.7).
I have figured out what's happening.
When you use std::getline() to read some text and then put it in a std::stringstream to process it with a while loop, you read exactly one line of text (up until the enter key) and then stop reading input.
When you use while(std::cin>>x) or use std::copy with a std::input_iterator it extracts information from std::cin until it gets to something it can't parse or until it gets to the end of the input - it skips ALL whitespace (including the enter key)
In this case we are reading int values so the std::getline()/std::stringstream/while method gets exactly one line of text and then the while contines extracting ints until the end of the input - in this case it's the end of the string we read.
But when using while(std::cin>>x) or std::copy what exactly indicates the end of the input? It isn't the enter key because that is whitespace. If you were redirecting the input from a file it would be the end of the file. But interactively, how do you make the end of the input from the keyboard?
Here's some more info:
The reason my samples worked on rextester.com is that you enter the input into a little box so it must be redirected in as a file - it isn't really interactive.