I have got an example for cplusplus.com for converting a string into a char array so i can split in into tokens and adds to a vector and it works fine in the main method but if i try and create a separate function and pass a string as a parameter, the program crashes with no explanation. It compiles fine.

Have i created the function type correctly? I want to create a vector of strings so i can output each vector.

// strings and c-strings
#include <iostream>
#include <cstring>
#include <string>
#include <vector>

using namespace std;

vector<string> SplitString (string aString)
{
  vector<string> vec;
  char * cstr, *p;

  //string str ("Please split this phrase into tokens");

  string str = aString;

  cstr = new char [str.size()+1];
  strcpy (cstr, str.c_str());

  // cstr now contains a c-string copy of str

  p=strtok (cstr," ");
  while (p!=NULL)
  {
    vec.push_back(p);
    p=strtok(NULL," ");
  }

  delete[] cstr;
}

int main ()
{
  std::vector<std::string> vec = SplitString("Please split this phrase into tokens");

  for (std::vector<std::string>::size_type a = 0; a < vec.size(); ++a)
  {
      cout << vec.at(a) << '\n'; 
  }	  
  return 0;
 
}
Member Avatar for iamthwee
// strings and c-strings
#include <iostream>
#include <cstring>
#include <string>
#include <vector>

using namespace std;

vector<string> SplitString (string aString)
{
  vector<string> vec;
  char * cstr, *p;

  //string str ("Please split this phrase into tokens");

  string str = aString;

  cstr = new char [str.size()+1];
  strcpy (cstr, str.c_str());

  // cstr now contains a c-string copy of str

  p=strtok (cstr," ");
  while (p!=NULL)
  {
    vec.push_back(p);
    p=strtok(NULL," ");
  }

  delete[] cstr;
  return vec;
}

int main ()
{
  std::vector<std::string> vec = SplitString("Please split this phrase into tokens");

  for (std::vector<std::string>::size_type a = 0; a < vec.size(); ++a)
  {
      cout << vec.at(a) << '\n'; 
  }	  
  
  cin.get();
  return 0;
 
}
commented: Solved my problem...thanks +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.