istream_iterator question

This is a discussion on istream_iterator question within the C++ Programming forums, part of the General Programming Boards category; Hi, I found this code that is supposed to enable user to enter a string of variable size from standard ...

  1. #1
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    712

    istream_iterator question

    Hi,
    I found this code that is supposed to enable user to enter a string of variable size from standard input by using istream_iterator. I understand how this works. Objects are extracted from an input stream and stored as string until end of file or some stream error is reached.
    Code:
    #include <iostream>
    #include <vector>
    #include <string>
    #include <algorithm>
    
    using namespace std;
    
    int main ()
    {
    	vector<string> v;
    	vector<string> ::const_iterator it;
    
    	copy(istream_iterator<string>(cin), 
    		istream_iterator<string>(),
    		back_inserter(v));
    
    	for (it = v.begin(); it != v.end(); ++it)
    	{
    		cout<<*it<<" ";
    	}
    }
    End of file is simulated by Ctrl-Z on Windows.
    I wonder how to make that input is finished either after user press Enter
    (i.e. when newline is input stream) or when eof is reached.
    Is it possible and how?
    I've just started to learn about STL and I'm pretty new to the concept of iterators.

    Thanks for help

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,806
    Code:
    #include <iostream>
    #include <vector>
    #include <string>
    #include <algorithm>
    #include <sstream>
    
    using namespace std;
    
    int main ()
    {
        vector<string> v;
        string temp;
    
        getline(cin,temp);
        stringstream str(temp);
        while( str >> temp )
            v.push_back(temp);
    
        copy(v.begin(),v.end(),ostream_iterator<string>(cout," "));
    
        return 0;
    
    }
    [edit]I simply chose to use another call to the copy function instead of the for loop for the output.[/edit]
    Last edited by hk_mp5kpdw; 03-14-2005 at 06:40 AM.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Nov 2001
    Posts
    1,348
    Another possible solution is string's begin()/end() functions. That elimates the need for the vector.

    Kuphryn

  4. #4
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    712
    Thanks

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21