strtok program crashing

前端 未结 4 1961
旧时难觅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:52

    aJ said what is needed. My advice is avoid that ugly & unsafe strtok. You are using C++ so go ahead with std::string. You also can use Boost http://www.boost.org/doc/libs/1_43_0/libs/libraries.htm#String & http://www.boost.org/doc/libs/1_43_0/doc/html/string_algo.html . If you want a new string class, you may look at http://bstring.sourceforge.net/ .

    0 讨论(0)
  • 2020-12-19 23:54

    char *line is a pointer and you are pointing it to a constant string ("LINE TO BE SEPARATED"). This fails when strtok attempts to modify that string. It would be better to qualify this variable as const char *line—still wouldn't work, but might lead to a helpful warning when you try to pass it to strtok.

    Meanwhile the array char line[] can be modified (it's not const) and is only initialised to contain the string.

    0 讨论(0)
  • 2020-12-19 23:56

    strtok modifies the input string line.

    char *line = "LINE TO BE SEPARATED";
    

    In this case line points to the read-only memory. Hence, cannot be modified. You need to pass char array for strtok.

    0 讨论(0)
  • 2020-12-19 23:56

    Since this has a C++ tag:

    // Beware, brain-compiled code ahead!
    #include <string>
    #include <sstream>
    #include <iostream>
    
    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 <string>
    #include <sstream>
    #include <iostream>
    #include <algorithm>
    
    int main()
    {
      std::istringstream iss("LINE TO BE SEPARATED");
      std::copy( std::istream_iterator<string>(std::iss)
               , std::istream_iterator<string>()
               , std::ostream_iterator<string>(std::cout, "\n") );
      return 0;
    }
    

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

    0 讨论(0)
提交回复
热议问题