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.
arr[i]
to be read RIGHT AFTER the user type the space after? That is a bit strange. Does it make a difference in the final goal you want to achieve? Can you elaborate what are you doing on top of this (if possible)?#include <bits/stdc++.h>
? and maybe this Why is “using namespace std;” considered bad practice?. And note that C and C++ are two different languages.