istream_iterator copy example keeps waiting for input

我怕爱的太早我们不能终老 提交于 2021-02-04 08:15:06

问题


I tried implementing an example of stream iterators from page 107 of "The C++ Standard Library". I get stuck on this line:

copy (istream_iterator<string>(cin), istream_iterator<string>(), back_inserter(coll)); 

The program keeps reading data from the console here, but does not pass on to the next line. How do I continue past this point?


回答1:


take for instance, if you would have made an input stream of int then you would have given input like - 45 56 45345 555 ....., so in all those cases, the reading operation of input stream would have returned a true value - while (cin>>var) { } the while statement will not stop if it is getting a valid input, so to stop the reading of characters, we gave it following input, ... 54 56 3545 | , and as soon as it receives a special character the while loop stops as the conditions returns false.

That's the same case for all other type of input streams as well.

So I assume you understand here why your string type input stream never stops taking input because every possible input can be considered string.

The solution to this problem is using "ctrl + D in UNIX" and "ctrl + Z in windows", as it gives NULL in condition of while loop which means false, hence stoping the reading of string input.




回答2:


From cppreference:

The default-constructed std::istream_iterator is known as the end-of-stream iterator. When a valid std::istream_iterator reaches the end of the underlying stream, it becomes equal to the end-of-stream iterator. Dereferencing or incrementing it further invokes undefined behavior

bold added

In other words, std::istream_iterator<string>(std::cin) keeps going until the end-of-input for std::cin. This doesn't happen at the end of the line, but at the end-of-file. In a console, there are specific commands to trigger the EOF:

In UNIX systems it is Ctrl+D, in Windows Ctrl+Z.



来源:https://stackoverflow.com/questions/50265390/istream-iterator-copy-example-keeps-waiting-for-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!