开发者

problem strtok in c++

i have a problem in strtock in c++ i need to read the follwing line from file

6:00,6:20,6:40,7:00,7:20,7:40,8:00,8:50,9:40,10:30,11:20,12:00 the length of the line is unknow(开发者_如何学JAVAi dont know how many arguments i have);

i try to do this function:

void RailwayLine::initilizeLoz(char line[1024])
 {

  char * pch;
  char * timeReader;
  Hour *hour;
  char * pch2=NULL;
  int time;
  int minute;
  char line2[1024];
  strcpy(line2,line);
  pch = strtok (line2,",");
 while (pch != NULL)
   {
    delete pch2;
    pch2= new char(strlen(pch)+1);
    if(pch2!=NULL)
   strcpy(pch2,pch);
    timeReader = strtok (pch2,":");
    time=atoi(timeReader);
    timeReader = strtok (NULL,":");
    minute=atoi(timeReader);
    hour=new Hour(time,minute);

           this-> UpdateLoz((*hour));

             pch=strtok(NULL,",");


   }


 }

but it didn't works. itj reads only the first argument (7:10)! what can be the froblem? how can i improve my code? thank you


You can't have nested strtok calls because the function keeps internal state between calls. Use strtok_r instead.


The absolute best way you could improve your code is to stop using stroke and use something that leverages the power of the language you're using. Boost has a tokenizer and other libraries that might actually meet your needs better (like regex).

The stroke in stroke isn't the fun kind; it's the kind you get in your brain. Terrible, terrible function that's design dates back to the dark ages of programming. It's got severe and permanent issues that render it not just obsolete, but dangerous...as you are seeing here. Stop trying to build things by tyeing rocks and sticks together. Come into the modern age where we've got forges and robotics. Save your brain!


I'd use a Boost Split or Tokenizer algorithm. But if you don't have Boost available, you could do something like this:

std::istringstream iss(line);
std::string departure;
while (getline(iss, departure, ','))
{
    // departure has one time in it;
    // do what you will with it
}


I don't think you can nest the strtok as you have done - when you fire up the search for the ":" it forgets about the previous instance you had going for picking out the comma separated items.


This would do the job.

 
void tokenize( std:: string stringToTokenize ) {

    char* pch = new char [ (stringToTokenize.length()) + 1 ];

    std:: strcpy( pch, stringToTokenize.c_str() ) ;

    pch = std:: strtok( pch, "," ) ;

    std::cout << std::endl ;

    while( pch != NULL ) {

    std::cout << pch << std::endl ;
    pch = strtok( NULL, "," ) ;

    }

}

int main( int argc, const char* argv[] ) {

std:: string s1 ; std:: getline( std::cin, s1 ) ; tokenize( s1 ) ; return 0 ;

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜