strtok program crashing

◇◆丶佛笑我妖孽 提交于 2019-11-29 11:55:01

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.

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.

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.

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/ .

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!