3

イテレータを介して文字列を読み取ることが、直接読み取ることとどのように異なるのか正確にはわかりません。例として、以下のコードを検討してください。

#include <iostream>
#include <string>
#include <iterator>

using namespace std;

int main() 
{
    string str{istream_iterator<char>(cin),{}};
    cout << str << endl;

    string str1;
    cin >> str1;
    cout << str1 << endl;
}

それが何をするかは明らかで、strを使用して読み取り、従来の方法istream_iteratorで読み取ります。str12 つの質問があります。

  1. 文字列反復子を介して読み取りを終了する唯一の方法は、CTRL+D(Unix) を送信することです。これもプログラムを終了させるため、2 番目の部分は実行されません。これを回避する方法はありますか?
  2. イテレータで読み取る場合、空白 (スペース、\t、\n) を入力してもイテレータは読み続けます。この動作が を介して直接読み取るときの動作と異なるのはなぜcin >>ですか?
4

2 に答える 2

3

I don't understand exactly how reading a string via iterators is different from reading it directly.

The difference in your example is that the first reads the entire stream, while the second reads a single word (until the first space).

More generally, iterators can be used to fill other containers (e.g. using istream_iterator<int> to fill vector<int>), or passed directly to algorithms that work with forward iterators.

The only way of ending the reading via string iterators is to send a CTRL+D (Unix), which also terminates the program

It doesn't terminate the program, it just closes the input stream. But you won't be able to read anything else from the input after doing that; as it stands, your program doesn't make sense since it tries to read beyond the end of cin.

When reading with iterators, it doesn't matter if I input whitespaces (space, \t, \n), the iterator keeps reading. Why is this behaviour different from the one when reading directly via cin >>?

Because that's how >> is defined to work with strings.

于 2014-08-06T14:16:09.030 に答える