I have a string which i can break down into tokens but what i want it to do is if it reaches a '//' it breaks out of the loop so no more tokens are added

I have tried using this but it doesn't work

while (p!=NULL)
{
    if(p=="//")
    {
    	break;
    }
    else
    {
	vec.push_back(p);
    	p=strtok(NULL," ");
    }
}

here is the full code

// 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)
  {
    // i presume a check must be done here
    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 // this bit needs to be ignored");

  for (std::vector<std::string>::size_type a = 0; a < vec.size(); ++a)
  {
      cout << vec.at(a) << '\n'; 
  }	  
  return 0;
 
}

Have you tried using the following as the condition for the while loop

while (p!=NULL && p!="//")

Then get rid of the if/else and just make the code currently after the else, the text of the while loop. It seems to me this is what you want the loop to do. Please correct me if I'm wrong.

Didn't work....i think i tried that already

I've also tried

while (p!=NULL)
{
unsigned int pos = str.find("//", 0);
if(pos != string::npos)
	break;
else
	vec.push_back(p);
	p=strtok(NULL," ");
}

but that doesn't output anything so i guess it's found the // and broke out of the loop

This article has been dead for over six months. Start a new discussion instead.