Manish Sharma
Manish Sharma

Reputation: 142

input unknown number of variables in one line(In C++)

I want to take input in vector of unknown number of numbers in one line. For instance 3 1 1 2 Here I know from first input that there are 3 numbers. But I dont know how to store the 3 numbers in the next line in a vector array. Another instance- 4 2 3 2 3 I want this in C++(vector).

Upvotes: 0

Views: 3382

Answers (3)

Shadow
Shadow

Reputation: 4016

Try this, works for me:

#include <vector>
#include <sstream>

vector<int> numbers;
string str;
int x;

getline (cin, str);
stringstream ss(str);
while (ss >> x)
    numbers.push_back(x);

If I enter something like:

1 2 3 4 5

The vector contains exactly those numbers, and goes on to execute the next line of code, instead of looping back to get more input from the user

Upvotes: 1

Kastaneda
Kastaneda

Reputation: 749

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

int main()
{
    int count = 0;
    std::cin >> count;
    // check that count is correct

    std::vector<int> vec;

    // input
    std::copy_n(std::istream_iterator<int>(std::cin), count, std::back_insert_iterator<std::vector<int> >(vec)); // std::copy_n is part of C++11

    // show vector
    std::copy(std::begin(vec), std::end(vec), std::ostream_iterator<int>(std::cout, " ")); // std::begin() and std::end() are part of C++11

    return 0;
}

Upvotes: 1

Tony Delroy
Tony Delroy

Reputation: 106126

int n, x;
std::vector<int> v;
if (std::cin >> n)
    while (n--)
        if (std::cin >> x)
            v.push_back(x);
        else
            throw std::runtime_error("missing value");
else
    throw std::runtime_error("missing count");

Upvotes: 5

Related Questions