-6

I want to convert the string str = "12 13 15 20" into array of integers like int str_int[4]{12,13,15,20} using c++.

Edward A
  • 2,291
  • 2
  • 18
  • 31

1 Answers1

2

You can use stringstream:

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

int main()
{
    std::string s = "12 13 15 20";
    std::stringstream ss( s);

    int i;
    std::vector<int> v;

    while( ss >> i)
        v.push_back( i);

    std::copy( v.begin(), v.end(), 
                             std::ostream_iterator<int>( std::cout, ","));
    return 0;
}

Another option is:

std::copy( std::istream_iterator<int>( ss), std::istream_iterator<int>(),     
                                                   std::back_inserter(v));
4pie0
  • 29,204
  • 9
  • 82
  • 118