簡體   English   中英

使用istream_iterator迭代int和string

[英]Iterating over int and string with istream_iterator

我將通過C ++編程語言手冊並到達“迭代器和I / O”第61頁,他們給出了以下示例來演示迭代提交的字符串。

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

using namespace std;

int main()
{

    istream_iterator<string>ii(cin);
    istream_iterator<string>eos;

    string s1 = *ii;
    ++ii;
    string s2 = *ii;

    cout <<s1 << ' '<< s2 <<'\n';
}

我完全理解,現在我正在玩這個例子,使它也適用於數字。 我嘗試在各自的地方添加以下內容......

istream_iterator<int>jj(cin);
int i1 = *jj;
cout <<s1 << ''<< s2 << ''<< i1 <<'\n';

這使我沒有機會在運行程序時輸入數字部分。 為什么會這樣? 迭代器只能在cin上使用一次嗎? 這樣它已經有來自cin輸入所以忽略下一個迭代器?


這里編輯是我插入后的內容

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

using namespace std;

int main()
{

    istream_iterator<string>ii(cin);
    istream_iterator<string>eos;

    //istream_iterator<int>dd(cin);

    string s1 = *ii;
    ++ii;
    string s2 = *ii;
    //int d = *dd;
    int d =24;
    cout <<s1 << ' '<<s2<<' '<<d<< '\n';
}

以上工作原理

Hello World
你好
世界

給Hello World作為輸出。

刪除評論

istream_iterator<int>dd(cin);
int d = *dd;

和評論

int d =24;

導致Hello Hello 0作為輸出。

首次創建istream_iterator時,它會獲取第一個輸入並在內部存儲數據。 為了獲得更多數據,您可以調用operator ++。 所以這是你的代碼中發生的事情:

int main()
{

    istream_iterator<string>ii(cin);  // gets the first string "Hello"
    istream_iterator<int>jj(cin); // tries to get an int, but fails and puts cin in an error state

    string s1 = *ii; // stores "Hello" in s1
    ++ii;            // Tries to get the next string, but can't because cin is in an error state
    string s2 = *ii; // stores "Hello" in s2
    int i1 = *jj;    // since the previous attempt to get an int failed, this gets the default value, which is 0

    cout <<s1 << ' '<<s2 <<' '<< i1 << '\n';
}

這是你想要做的:

int main()
{

    istream_iterator<string>ii(cin);

    string s1 = *ii;
    ++ii;
    string s2 = *ii;

    istream_iterator<int>jj(cin);
    int i1 = *jj;

    // after this, you can use the iterators alternatingly,
    //  calling operator++ to get the next input each time

    cout <<s1 << ' '<<s2 <<' '<< i1 << '\n';
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM