Crystal
Crystal

Reputation: 29448

getting input numbers from the user

How can I get input from the user if they are to separate their inputs by whitespace (e.g. 1 2 3 4 5) and I want to put it in an array? Thanks.

Hmmmm. I see most of the responses are using a vector which I guess I'll have to do research on. I thought there would be a more simpler, yet possibly messier response since we haven't covered vectors like using sscanf or something. Thanks for the inputs.

Upvotes: 4

Views: 314

Answers (3)

Pentium10
Pentium10

Reputation: 207830

#include <vector>
#include <iostream>
using namespace std;

int main()
{
   vector<int> num;
   int t;
   while (cin >> t) {
     num.push_back(t);
   }
}

Upvotes: 2

Eugen Constantin Dinca
Eugen Constantin Dinca

Reputation: 9130

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

   std::istream_iterator< int > iterBegin( std::cin ), iterEnd;
   std::vector< int > vctUserInput( iterBegin, iterEnd );

Upvotes: 1

dirkgently
dirkgently

Reputation: 111120

Alternatively, and a more generic form:

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;

int main()
{
   vector<int> num;

   copy(istream_iterator<int>(cin), istream_iterator<int>(), back_inserter(num));
}

Upvotes: 1

Related Questions