0

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?

2
  • 1
    did you try something? If yes, show some code. Commented Oct 25, 2019 at 23:32
  • Welcome to SO. Coding assignments are designed to help you grasp fundamental concepts. You should attempt an answer yourself first and post it. You will learn from the exercise, of creating the code plus you will receive valuable feedback from this site regarding things you can do to improve the code. Commented Oct 25, 2019 at 23:54

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

5 Comments

The number of elements must be on the same line, but thanks to your help, it will be easier for me now.
So, where in the code do I specify any line separations? The std::cin function ignores whitespace; so the numbers can be space separated on one line or one number per line.
Is it possible if I do not enter any characters and press enter to stop entering the data?
The input will stop after you enter the specified quantity of numbers. If your first number is 3, you will need to enter 3 numbers.
I managed to get the idea int a, b; cin >> a; cin >> b; it is the same as cin >> a >> b; _______ cin >> capacity Array [0] = x1; Array [1] = x2; .... cin >> capacity >> x_1 >> x_2; Thanks man!
2

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>()
);
*/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.