Reading elements for a vector until EOL I'm a novice to programming completely. I'm trying to teach myself C++. I want to write code to create two vectors and read their elements from input.

vector&lt;int&gt; v1, v2;
/*Reading vector values*/
cout &lt;&lt; "Enter the elements of 1st vector" &lt;&lt; endl;
int ele;
while (cin &gt;&gt; ele)
    v1.push_back(ele);
cout &lt;&lt; "enter the elements of 2nd vector" &lt;&lt; endl;
while (cin &gt;&gt; ele)
    v2.push_back(ele);


Though it basically does what I coded it for, I want to have some improvements.


When I input elements into a vector, I would like Enter key to mean that I'm done entering the vector, while a space key says I'm entering the next element.
How can I write a loop for vector 1 and vector 2, as the code for entering elements is the same for both the vectors? (I want to write a loop for reading the two vectors.)
Perhaps the simplest solution is to read the input line and parse it. You are also correct it is a good idea to write a function for reading a vector.

Consider the following:

#include &lt;iostream&gt;
#include &lt;string&gt;
#include &lt;sstream&gt;
#include &lt;vector&gt;
#include &lt;iterator&gt;

std::vector&lt;int&gt; read_vector()
{
    std::string line = "";
    std::getline(std::cin, line);
    std::istringstream iss(line);

    std::vector&lt;int&gt; v;

    int x = 0;
    while (iss &gt;&gt; x)
        v.push_back(x);

    return v;
}

int main()
{
    std::cout &lt;&lt; "Enter the elements of 1st vector\n";
    std::vector&lt;int&gt; v1 = read_vector();

    std::cout &lt;&lt; "Enter the elements of 2nd vector\n";
    std::vector&lt;int&gt; v2 = read_vector();

    std::cout &lt;&lt; "v1 = { ";
    for (auto e : v1)
        std::cout &lt;&lt; e &lt;&lt; " ";

    std::cout &lt;&lt; "}\nv2 = { ";
    for (auto e : v2)
        std::cout &lt;&lt; e &lt;&lt; " ";
    std::cout &lt;&lt; "}";
}


The functionality of reading a vector is now found from read_vector; quite obviously, it reads the input string (until the delimiter, which is by default an end of the line), and reads space-separated integers, pushes them to the vector, and returns it.