strtok program crashing

前端 未结 4 1989
旧时难觅i
旧时难觅i 2020-12-19 23:15

the program for strtok given on http://www.opengroup.org/onlinepubs/000095399/functions/strtok.html crashes everytime..

#include 
...
char *t         


        
4条回答
  •  抹茶落季
    2020-12-19 23:56

    Since this has a C++ tag:

    // Beware, brain-compiled code ahead!
    #include 
    #include 
    #include 
    
    int main()
    {
      std::istringstream iss("LINE TO BE SEPARATED");
      while( iss.good() ) {
        std::string token;
        iss >> token;
        std::cout << token '\n';
      }
    
      return 0;
    }
    

    Edit: As Konrad said in his comment, the above loop could be replaced by std::copy working on stream iterators:

    // Beware, brain-compiled code ahead!
    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
      std::istringstream iss("LINE TO BE SEPARATED");
      std::copy( std::istream_iterator(std::iss)
               , std::istream_iterator()
               , std::ostream_iterator(std::cout, "\n") );
      return 0;
    }
    

    I have to (grudgingly) admit that there's something to be said for it.

提交回复
热议问题