How to take input in a single line in C++?

I want to take the input of the size of the array and the elements of the array in the same line separated by spaces e.g. If the size is 5 and elements are 0,1,2,3,4.
Input form: 5 0 1 2 3 4

In this case, you can just largely ignore how the data is formatted: the only thing we care about is that the things we want to read are separated by whitespace:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int arraySize;
    cin >> arraySize;

    vector<int> array(arraySize);
    for (auto& element : array)
    {
        cin >> element;
    }

    cout << "Array: (" << arraySize << " elements)" << endl;
    for (const auto& element : array)
    {
        cout << element << endl;
    }
}

This will give the same output irrespective of whether the elements are on the same line or not:

$ echo "5 1 3 4 5 6" | ./a.out 
Array: (5 elements)
1
3
4
5
6
$ echo "5
1 3 4 5 6" | ./a.out
Array: (5 elements)
1
3
4
5
6
3 Likes
int n; cin >> n;
for (i, 0, n) cin >> array[i];
1 Like

Take input a list/array in few lines:

int n; cin >> n;
vector<int> a(n);
for (int &x : a) cin >> x;

what if we didn’t know size of array just like python?

Do you mean, “what if the size of the array is not provided in the input?”, i.e. you just have a single line, containing only the elements in the array and not the size?

1 Like

oh yes :slight_smile: … (20 char hueeeerrrrr)

1 Like

I’d probably do something like:

#include <vector>
#include <sstream>

using namespace std;

int main()
{
    string line;
    getline(cin, line);
    istringstream lineStream(line);

    int value;
    vector<int> array;
    while (lineStream >> value)
    {
        array.push_back(value);
    }

    cout << "Array: (" << array.size() << " elements)" << endl;
    for (const auto& element : array)
    {
        cout << element << endl;
    }
}
$ echo "11 7 6 1 8" | ./a.out
Array: (5 elements)
11
7
6
1
8

Edit:

Or if you want to read multiple lines:

#include <iostream>
#include <vector>
#include <sstream>

using namespace std;

int main()
{
    string line;
    while (getline(cin, line))
    {
        istringstream lineStream(line);

        int value;
        vector<int> array;
        while (lineStream >> value)
        {
            array.push_back(value);
        }

        cout << "Array: (" << array.size() << " elements)" << endl;
        for (const auto& element : array)
        {
            cout << element << endl;
        }
    }
}
$ echo "11 7 6 1 8
22 98 7 6 5 5 7 2332 33 3
67 8383 73 736 3 33" | ./a.out
Array: (5 elements)
11
7
6
1
8
Array: (10 elements)
22
98
7
6
5
5
7
2332
33
3
Array: (6 elements)
67
8383
73
736
3
33
5 Likes