sunidhi chaudhary
sunidhi chaudhary

Reputation: 31

How to take input to an array with unknown number of elements?

int n = 10;
int a[n];  
for (int i = 0; i < n; i++)
{
    cin >> a[i];
}

This is how I input array when we know the size of n. But when we don't know the size of n and we have to take input in an array and stop taking inputs when there is a new line. How can we do that in C++?

Upvotes: 0

Views: 13718

Answers (4)

Jessica G.
Jessica G.

Reputation: 111

You will probably need a vector of type string unless you are using stoi(); So basically something like the code below.

int n = 10;
vector<string> a; 
string temp; 

while(cin>>temp)
{
   a.push_back(temp);
}

or

vector<int> a; 
while(cin>>temp)
    {
       a.push_back(stoi(temp));
    }

Upvotes: 1

Jonathan Mee
Jonathan Mee

Reputation: 38909

So this prevents you from doing error checking, but at least for my toy projects is to use vector with an istream_iterator So something like this:

const vector<int> a{ istream_iterator<int>{ cin }, istream_iterator<int>{} }

Live Example

Upvotes: 0

ritwikshanker
ritwikshanker

Reputation: 477

To stop taking input you need to use EOF Concept. i.e. End of File. Place the cin in a while loop. Something like this -

while (cin >> n)
{
  a.push_back(n);
}

Upvotes: 1

skeller
skeller

Reputation: 1161

std::vector<int> is what you need. Think of it as an array of dynamic size.

you can add elements to a vector by using .push_back()

see https://en.cppreference.com/w/cpp/container/vector

Upvotes: 3

Related Questions