开发者

Random Integer List

开发者_如何转开发If I had a list of integers separated by a space on one line (eg: 50 34 1 3423 5 345) then what would be the best way of making each of them a separate integer variable - collecting the list of integers with cin?


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

std::vector<int> ints;
std::copy(std::istream_iterator<int>(cin), 
      std::istream_iterator<int>(), 
      std::back_inserter(ints));

Done. If you really need to explicetely read line-wise:

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

std::string singleline;
std::istringstream iss; // out of loop for performance
while (std::getline(cin, singleline))
{
      iss.str(singleline);
      std::copy(std::istream_iterator<int>(iss), 
            std::istream_iterator<int>(), 
            std::back_inserter(ints));
}

An istream_iterator<int> will repeatedly apply operator>>(int&) to the referenced stream (until the end of the stream). By default this will silently ignore whitespace, and it will throw an exception if the input operation failed (e.g. non-integer input is encountered)

The back_inserter is an output iterator that you can use with all container types (like vector) that support the .push_back operation. So in fact what is written there in STL algorithmese is similar to

std::vector<int> ints;
while (iss>>myint)
{
     ints.push_back(myint);
}


In follow-up to sehe's answer, here's how you'd do it a little more verbosely (ahem).

The algorithms sehe used basically do this internally. This answer is included mostly for clarity.

#include <iostream>
#include <vector>

int main()
{
   std::vector<int> myInts;

   int tmp;
   while (std::cin >> tmp) {
      myInts.push_back(tmp);
   }

   // Now `myInts` is a vector containing all the integers
}

Live example.


Have a look at the man pages for strtok( ) and atoi( )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜