3

http://www.opengroup.org/onlinepubs/000095399/functions/strtok.html上给出的 strtok 程序每次都会崩溃。

#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);

如果我对变量“行”使用 char 数组,它可以工作。即 char line[] = "LINE TO BE SEPARATED" 有效。

请解释。

4

4 回答 4

8

strtok修改输入字符串line

char *line = "LINE TO BE SEPARATED";

在这种情况下line指向只读存储器。因此,无法修改。您需要将 char 数组传递给strtok.

于 2010-05-16T09:52:31.307 回答
2

因为它有一个 C++ 标签:

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

编辑:正如 Konrad 在他的评论中所说,上面的循环可以通过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;
}

我不得不(勉强)承认有话要说。

于 2010-05-16T10:38:44.123 回答
2

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.

于 2010-05-16T11:11:14.933 回答
1

aJ 说需要什么。我的建议是避免丑陋和不安全的 strtok。您正在使用 C++,因此请继续使用 std::string。您还可以使用 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。如果你想要一个新的字符串类,你可以查看http://bstring.sourceforge.net/

于 2010-05-16T09:58:30.513 回答