0
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++?

3
  • 4
    Use a std::vector rather than a fixed-size array. Commented Jun 22, 2018 at 11:22
  • There is no such thing as an "array of unknown size". To read unknown number of elements, consider using std::vector. Commented Jun 22, 2018 at 11:23
  • Possible duplicate of Why aren't variable-length arrays part of the C++ standard? Commented Jun 22, 2018 at 11:23

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

okay, but when I use vector<int> and push_back(), when will it stop taking input?
@sunidhichaudhary you could use special input for breaking the loop (e.g -1)
1

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);
}

Comments

1

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));
    }

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.