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

Ron
  • 14,674
  • 4
  • 34
  • 47
sunidhi chaudhary
  • 21
  • 1
  • 2
  • 10
  • 4
    Use a `std::vector` rather than a fixed-size array. – acraig5075 Jun 22 '18 at 11:22
  • There is no such thing as an "_array of unknown size_". To read unknown number of elements, consider using `std::vector`. – Algirdas Preidžius Jun 22 '18 at 11:23
  • Possible duplicate of [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – Joseph D. Jun 22 '18 at 11:23

4 Answers4

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

skeller
  • 1,151
  • 6
  • 6
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);
}
ritwikshanker
  • 456
  • 7
  • 19
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));
    }
Jessica G.
  • 101
  • 7
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

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288