I've newly started learning C++ and am stuck with this problem. I need to insert a (user inputted) number of elements in a single line with space separation. If the number of elements was known, I could just write cin >> var1 >> var2 >> ... >> varN;
. But how do I do it with any number of elements (loop maybe)?
This is what I'm trying to do:
#include<bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int arr[n];
for (int i=0; i<n; i++) {
//stuck here
}
}
I could have written cin >> arr[i];
and proceeded, but that would require the user to press enter after every input, which I cannot do due to the question's restrictions. How do I write the code so that all my input for array elements can be given in a single line?
PS: I've seen several similar questions already answered on the site, but most of them involve implementations using vectors or are beyond my current level of understanding. A simpler solution will be appreciated.
cin>>arr[i]
does not require the user to press enter after every input.
You just need to give whitespace between the integer inputs. It will scan the array normally.