0

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;
 
}
2
Contributors
1
Reply
12
Views
7 Years
Discussion Span
Last Post by iamthwee
0
// 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;
 
}

Edited by iamthwee: n/a

Votes + Comments
Solved my problem...thanks
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.