cin number input with space

When inputting a series of numbers with a space in between, cin merges the number together. I am wondering how I could separate put all the digits in a vector. I attempted to do this, but cin reads all the numbers merged.

ex. input is -> 1 2 3 4 5
The output expected was 1 to be in index 0 of the vector, 2 to be in index 1of the vector, - - -. However, 12345 is in index 0.

1
2
3
4
5
6
7
vector<int> v;
int num = 0, totalNums = 0;
cin >> totalNums;
for(int j = 0; j < totalNums; j++) {
    cin >> num;
    v[j] = num;
}


Thank you!
That should not be happening. cin>> reads an integer by first skipping whitespace and then reading characters up to the first non-digit character. So it stops reading at whitespace or any non-digit. It will not read a bunch of space-separated digits into a single int.

However, you are not appending the ints to the vector properly. The vector has no space allocated to it yet, so you can't just index it like that. You need to use push_back. Alternatively, you could resize() the vector to the correct size first and then index it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> v;
    int totalNums = 0;
    cin >> totalNums;
    for (int i = 0; i < totalNums; ++i) {
        int num;
        cin >> num;
        v.push_back(num);
    }
    for (int n: v) cout << n << ' ';
    cout << '\n';
}

Last edited on
Okay, now understood. Thank you so much!!!
Topic archived. No new replies allowed.