0

I have a question about istream iterators and reading the input to the EOL. How do you do it? I tried the following but had to revert to a hack to get it to work.

My first attempt reads from the istream but a word at a time.

first.cpp

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

int main(int argc, char** argv)
{
    std::vector<std::string> the_words;

    std::istream_iterator<std::string> in(std::cin);
    std::istream_iterator<std::string> CIN_EOF;

    while ( in != CIN_EOF )
    {
        the_words.push_back(*in);
        ++in;
    }

    std::vector<std::string>::const_iterator begin = the_words.begin();
    std::vector<std::string>::const_iterator end = the_words.end();
    std::vector<std::string>::size_type count = 0;

    while ( begin != end )
    {
        std::cout << "[" << ++count << "] - " << *begin << std::endl;
        ++begin;
    }

    return 0;
}

The output for the above code is:

this is the first
this is the second
this is the third
[1] - this
[2] - is
[3] - the
[4] - first
[5] - this
[6] - is
[7] - the
[8] - second
[9] - this
[10] - is
[11] - the
[12] - third

Note the code is reading a word then pushing it onto the vector the_words.

My second attempt works but I feel its a bit of a hack. Does anyone know a better way?

hack.cpp

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

class myc
{

public:

    operator std::string() const { return str; }

    std::string str;

};

std::istream& operator >>(std::istream & in, myc & m)
{
    return std::getline(in, m.str);
}

int main(int argc, char**argv)
{
    std::vector<std::string> the_words;

    std::istream_iterator<myc> in(std::cin);
    std::istream_iterator<myc> CIN_EOF;

    while ( in != CIN_EOF )
    {
        the_words.push_back(*in);
        ++in;
    }

    std::vector<std::string>::const_iterator begin = the_words.begin();
    std::vector<std::string>::const_iterator end = the_words.end();
    std::vector<std::string>::size_type count = 0;

    while ( begin != end )
    {
        std::cout << "[" << ++count << "] - " << *begin << std::endl;
        ++begin;
    }

    return 0;
}

The output from the hack works.

Hack output
this is the first
this is the second
this is the third
[1] - this is the first
[2] - this is the second
[3] - this is the third

The code now reads to the EOL and pushes the results onto the vector the_words.

Does anyone know a better way to do this? My solution seems so hacky....Please delete my first attempt at using your new editors.

Edited by gerard4143

1
Contributor
1
Reply
2
Views
4 Years
Discussion Span
Last Post by gerard4143
0

Odd I thought someone would have some comments on this code. I guess the second attempt 'the hack' is acceptable code.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.