tags:

views:

96

answers:

3

I have string with number on ints seperated by space delimiter. Can some one help me how to split the string into ints. I tried to use find and then substr. Is there a better way to do it ?

+2  A: 

Use a stringsteam:

#include <string>
#include <sstream>

int main() {
    std::string s = "100 123 42";
    std::istringstream is( s );
    int n;
    while( is >> n ) {
         // do something with n
    }
}
anon
if there is only two values like 100 123 every time is there a better way to do it ?
brett
@brett What do you mean by "better"?
anon
Simple and elegant...
Andrejs Cainikovs
If there's always two numbers, you can do: `int x, y; is >> x >> y;` to extract them both without a loop.
reko_t
@Neil thank you very much
brett
@Neil, do you never sleep?
tholomew
+1  A: 

This has been discussed as part of http://stackoverflow.com/questions/236129/c-how-to-split-a-string

Also, you can use boost library split function to achieve the splitting without a loop in your program. Eg.

boost::split(epoch_vector, epoch_string, boost::is_any_of(","));

Kisalay
A: 

A version using boost. The stringstream version from Neil is so much simpler!

#include <iostream>
#include <vector>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>

int main()
{
  const std::string str( "20 30 40 50" );
  std::vector<int> numbers;
  boost::tokenizer<> tok(str);
  std::transform( tok.begin(), tok.end(), std::back_inserter(numbers), 
                  &boost::lexical_cast<int,std::string> );
  // print them
  std::copy( numbers.begin(), numbers.end(), std::ostream_iterator<int>(std::cout,"\n") ); 
}
Brian O'Kennedy
You don't even need boost for this. You can simply construct an instance of `std::istringstream is(str);` and then do `std::copy(std::istream_iterator<int>(is), std::istream_iterator<int>(), std::back_inserter(numbers));`
reko_t
@reko_t Nice! Does the istream_iterator expect space delimited items, or can it also handle other delimiters?
Brian O'Kennedy
It expects space delimited items, it can't handle other delimiters.
reko_t