Dino
Dino

Reputation: 8292

Input in same line which is based on previous input

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.

Upvotes: 0

Views: 42

Answers (2)

William FitzPatrick
William FitzPatrick

Reputation: 133

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?

Upvotes: 0

Sid S
Sid S

Reputation: 6125

I would do it like this:

int n;
cin >> n;
vector<int> v(n);
for (auto &a : v)
{
    cin >> a;
}

Upvotes: 2

Related Questions