Strtok crash

The program for strtok given at http://www.opengroup.org/onlinepubs/000095399/functions/strtok.html crashes every time.

#include <string.h>
...
char *token;
char *line = "LINE TO BE SEPARATED";
char *search = " ";


/* Token will point to "LINE". */
token = strtok(line, search);


/* Token will point to "TO". */
token = strtok(NULL, search);

If I use a char array for the 'line' variable, it works. those. char line [] = "LINE TO SEPARATED" works.

Please explain.

+3
source share
4 answers

strtokchanges the input string line.

char *line = "LINE TO BE SEPARATED";

In this case, lineindicates a read only memory. Therefore, you cannot change. You need to pass a char array to strtok.

+9
source

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;
}

: , std::copy, :

// 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;
}

() , - .

+2

char *line , ("LINE TO BE SEPARATED"). , strtok . const char *line - , strtok.

char line[] ( const) , .

+2

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

+1
source

Source: https://habr.com/ru/post/1745622/


All Articles