0

How do we take input from user in C++ and store in vector when the number of elements is variable?

I know that when we know the number of elements we can use pretty much this code:

for(int i=0;i<n;i++)
{
   cin >> element;
   my_vector.push_back(element);
}

But in my case I don't know what the size is going to be, so how can I do this?

cigien
  • 57,834
  • 11
  • 73
  • 112

1 Answers1

2

You can keep looping and adding elements until the stream extraction fails:

while(cin >> element)
   my_vector.push_back(element);

The loop will terminate when there are no more elements of the appropriate type to be read from cin.

cigien
  • 57,834
  • 11
  • 73
  • 112