简体   繁体   中英

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(i 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
}

我不认为你可以按照你所做的那样嵌套strtok - 当你启动搜索“:”时它会忘记你之前选择逗号分隔项的实例。

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 ;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM