vmahth1
vmahth1

Reputation: 203

c++ creating array with input data

My task is to enter in one row of data, 1 number tells how many elements the array will have, the next tells what elements they will be. Before entering data I do not know how big a 3-element or 300 array can be. Example

Input 5 3 6 5 7 8 

Array1[5]={3,6,5,7,8}
If I press enter it initializes the next table Board2, like

Input 3 9 8 3
Array2[3]={9,8,3}

If he gets two enters, he will stop entering data. Can you help me with this?

Upvotes: 0

Views: 1714

Answers (2)

Thomas Matthews
Thomas Matthews

Reputation: 57678

You could try old school and allocate the array from dynamic memory after the capacity is read in:

int capacity = 0;
std::cin >> capacity;
int * array = new int[capacity];
for (int i = 0; i < capacity; ++i)
{
    std::cin >> array[i];
}
//...
delete [] array;

Upvotes: 2

Remy Lebeau
Remy Lebeau

Reputation: 595412

You can use a std::istringstream and std::vector for that, eg:

std::string input;
std::getline(std::cin, input);

std::istringstream iss(input);

int n;
iss >> n;

std::vector<int> vec(n);
for(int i = 0; i < n; ++i) {
    iss >> vec[i];
}

On the other hand, if you do use this approach, then you can omit the leading number altogether since std::vector can grow dynamically, so there is no eed to be explicit about the count of numbers in the input:

std::string input;
std::getline(std::cin, input);

std::istringstream iss(input);
int i;

std::vector<int> vec;
while (iss >> i) {
    vec.push_back(i);
}
/* Alternatively:
std::vector<int> vec(
  std::istream_iterator<int>(iss),
  std::istream_iterator<int>()
);
*/

Upvotes: 2

Related Questions