我认为这是第一次失败的召唤。我写了C已经有一段时间了,我不知所措。非常感谢。
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
char *str = "one|two|three";
char *tok = strtok(str, "|");
while (tok != NULL) {
printf("%s\n", tok);
tok = strtok(NULL, "|");
}
return 0;
}
答案 0 :(得分:7)
字符串文字应该分配给const char *,因为修改它们是未定义的行为。我很确定strtok会修改它的参数,这可以解释你看到的坏事。
答案 1 :(得分:2)
有两个问题:
制作str
类型的char[]
。 GCC会发出警告foo.cpp:5: warning: deprecated conversion from string constant to ‘char*’
,表明这是一个有问题的行。
您的第二个strtok()
来电应该有NULL
作为其第一个参数。请参阅docs。
生成的工作代码为:
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
char str[] = "one|two|three";
char *tok = strtok(str, "|");
while (tok != NULL) {
printf("%s\n", tok);
tok = strtok(NULL, "|");
}
return 0;
}
输出
one
two
three
答案 2 :(得分:0)
我不确定“总线”错误是什么,但是如果你想继续解析相同的字符串,那么循环中strtok()的第一个参数应为NULL。
否则,在第一次调用strtok()之后,你继续从相同字符串的开头开始,顺便说一句,这已被修改。