vendredi 8 mai 2015

C++: Parsing with strtok and creating char* array

I have a problem today with parsing a string, and, although I have used strtok previously, I came across a problem. My code looks like this>

int main()
{
char *arr[8]; //create a pointer to array of 8 elements
string data;

cout<<"please input string "<<endl;
cin>> data;

ifstream in(data.c_str());
    if (in.is_open()) {
        cout<<"opened"<<endl;
    } else{
        cout<<"can't open the file you asked for"<<endl;
    }

std::string line;

while(getline(in,line)) {
        if(line.find("STR") == 0) { //looking only for lines that start with STR

  char *forParsing = new char[line.size()+1];
  std::copy(line.begin(), line.end(), forParsing);
  forParsing[line.size()]='\0';  //everything looks good up to here

  char * pch;

  pch = strtok (forParsing,","); //separate input string on every comma
  while (pch != NULL)
  {
     arr[x] = pch; x++;  //x previously initialized to zero
     cout<<pch<<endl;
     pch = strtok (NULL, ",");
  }

  delete[] forParsing;
} //end if
} //end while

After some debugging, it seems to me that strtok does it's work on a first line it gets. After that, program takes a next line from a file and then entire thing crashes.

My plan with this is to put all the non-empty tokens in arr, then do some light editing, and collect it all into one string that will later be used.

Does anyone have any idea why is this happening?

Thanks in advance.

NOTE> if its of any importance Process return 255(0xFF) when it crashes.

Aucun commentaire:

Enregistrer un commentaire