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<int> v1, v2;
/*Reading vector values*/
cout << "Enter the elements of 1st vector" << endl;
int ele;
while (cin >> ele)
cout << "enter the elements of 2nd vector" << endl;
while (cin >> ele)

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

  1. 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.

  2. 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.)

  • 1
    \$\begingroup\$ Although it's too late to edit now that you've received an answer, it's worth noting for the future that you'll receive better reviews if you post code that's more complete. For example, I recommend that you show the necessary #include lines, and the using std::vector; and similar that we must assume. It's not mandatory, but it really helps! \$\endgroup\$ – Toby Speight Mar 14 '17 at 10:58

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 <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>

std::vector<int> read_vector()
    std::string line = "";
    std::getline(std::cin, line);
    std::istringstream iss(line);

    std::vector<int> v;

    int x = 0;
    while (iss >> x)

    return v;

int main()
    std::cout << "Enter the elements of 1st vector\n";
    std::vector<int> v1 = read_vector();

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

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

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

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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.