tags:

views:

108

answers:

3

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.

+2  A: 
#include <vector>
#include <iostream>
using namespace std;

int main()
{
   vector<int> num;
   int t;
   while (cin >> t) {
     num.push_back(t);
   }
}
Pentium10
1) You need to #include <iostream>.2) For such a simple example I don't see the need of using namespace std, you can simply say std::vector and std::cin.3) You don't really need the curly braces around the push_back.
Alexandros Gezerlis
Thank you, I've added iostream. I bet the requester is newbie, and it would be easier to mention using namespace rather than prefixing them.
Pentium10
+1  A: 

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));
}
dirkgently
The OP asked about putting the input into an array, not a vector (this applies to Pentium10's answer, too).
Alexandros Gezerlis
The vector is the array in CPP.
Pentium10
The reason I use a `vector` is because you don't know how many numbers you'll need to store beforehand. If you did, it'd make sense to use an array. Otherwise, you'd need a loop to test for index out-of-range before inserting in the array.
dirkgently
+1  A: 
#include <iostream>
#include <iterator>
#include <vector>

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