kevin4z - 4 months ago 14

C++ Question

- Assume the following numbers are inputed in VC++ Console(separate with a
**space**). N maybe 10, 20 or 100, it is uncertain.

`1 2 3 4 ... N [Enter]`

- The number of inputs is uncertain, maybe 10, or 20. After I press the
**Enter**key, how put these numbers into an Array?

`array[0]=1; array[1]=2; ...`

How to implement that with C++ code?

Answer

As *PeterT* pointed out, If you don't know the size of the array ahead of time, you'll have to use *dynamic memory allocation*. Luckily, the *STL* has a container that does it for you.

You can use `std::vector`

for that job.

```
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main() {
std::string nums; // the numbers in the format "1 2 3 4 10 -20"
std::getline(std::cin,nums);
std::stringstream stream(nums);
int n;
std::vector<int> vec;
while(stream >> n) {
vec.push_back(n);
}
return 0;
}
```

(code is based on *Abdulla Al Sun*'s answer.)

This is an O(n) (linear complexity) solution.

If you want to convert it in to an actual array, you can do:

```
int array[vec.size()];
std::copy(vec.begin(), vec.end(), array);
```

Another approach is to figure out how many elements the user inputted by storing his input in a string, and counting the tokens.

Then you know how big of an array you need.

```
unsigned int getSize(std::string s) {
unsigned int size = 0;
std::stringstream ss(s);
int in;
while (ss >> in)
++size;
return size;
}
int main() {
std::string nums; // the numbers in the format "1 2 3 4 10 -20"
std::getline(std::cin,nums);
const unsigned int size = getSize(nums);
int array[size];
std::stringstream stream(nums);
int n;
for(unsigned int i = 0; stream >> n && i < size; ++i) {
array[i] = n;
}
return 0;
}
```

This is an O(2n) (linear complexity) solution.