Cin flow endless loop why?

I copied this simple program from the C ++ programming language, but I cannot make it work as I wish. Am I missing something? Basically, the program will output the “input end” after I press “return” and then repeat the input from cin. He can never proceed to the next statement. I tried using a vector (commented on two statements below), same thing. I tried on Vc6 and vs2008.

    #include <iostream>
#include <map>
#include <algorithm>
#include <string>
#include <iterator>
#include <vector>
using namespace std;

map<string, int> histogram;
void record(const string &s)
{
    histogram[s]++; //this is pretty strange, however it does work!
    cout<<"recorded:"<<s<<" occurance="<<histogram[s]<<"\n";
}

void print(const pair<const string,int> &r)
{
    cout<<r.first<<' '<<r.second<<'\n';
}

int main()
{
    istream_iterator<string> ii(cin);
    istream_iterator<string> eos;
    cout<<"input end\n";

    for_each(ii,eos,record); //this statement cannot get out why? It repeats the keyboard input
    //vector<string> b(ii,eos);
    //for_each(b.begin(),b.end(),record);
    for_each(histogram.begin(),histogram.end(),print); //program never comes here why?
}

Execution of results:

abc

input end

written: randomness = 1

: b occurance = 1

recorded: c occurance = 1

1 2 3

recorded: 1 occurance = 1

recorded: 2 occurance = 1

: 3 occurance = 1

+5
source share
1 answer

istream_iterator , , cin .

cin , , ( ) , -, CTRL-Z (CTRL-D Linux, iirc). , Enter .

, cin , .

, ii ( ).

, for_each, while, , , , .

+5

All Articles