0

I have a simple input which takes one integer.

int n
std::cin >> n
vector<int> vec;

What I would like to do next, is to accept 'n' number of integers all from the same line, and add them to the 'vec' vector.

So if my first input is 3, my next input should accept 3 numbers from the same line:

3
6 1 2

I tried using the for loop, but it obviously won't make those inputs come from the same line.

for(int i = 0; i < n; i++){
  std::cin >> ...
}

What's the proper way to do this?

In Java I would simply put Java.util.Scanner.nextInt() in the for loop.

1
  • This should work the way you have it if the inputs are in fact on the same line. Or do you want to reject or ignore input with too few or too many numbers on a line or something? Commented Jan 13, 2018 at 23:26

2 Answers 2

2

I would do it like this:

int n;
cin >> n;
vector<int> v(n);
for (auto &a : v)
{
    cin >> a;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Using std::cin can grab multiple integers from the same line using a for loop. However, if the user hits enter, a newline will appear. There are more complex/efficient ways of doing this like using an iterator and a reference in the for loop, but this way is easier to understand if you are new to the language.

int n;
std::cin >> n;
std::vector<int> vec;
for (int i = 0; i < n; i++) {
    int integer;
    std::cin >> integer;
    vec.push_back(integer);
}

If you really want to input variables without creating a new line, look at this link: How do I input variables using cin without creating a new line?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.