[英]How split a string in c with comma
I created a function to split a string with comma.我创建了一个 function 来用逗号分割字符串。
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
char splitted_line[8][50];
void split(char *line){
printf("line 9\n");
char *part = strtok(line, ",");
printf("line 11\n");
for(int i=1; i<8; i++){
strcpy(splitted_line[i], part);
printf("%s\n", splitted_line[i]);
part = strtok(NULL, ",");
}
}
int main(){
char *line = "123,456,789";
split(line);
return 0;
}
but the result after running is:但运行后的结果是:
line 9
Segmentation fault (core dumped)
it seems the problem is in char *part = strtok(line, ",");
似乎问题出在
char *part = strtok(line, ",");
but I don't know what's that.但我不知道那是什么。
strtok()
will modify passed original string directly. strtok()
将直接修改传递的原始字符串。
You must not modify string literals.您不得修改字符串文字。
char *line = "123,456,789";
should be modifyable array应该是可修改数组
char line[] = "123,456,789";
Also don't forget to check if part
is not NULL
before doing strcpy(splitted_line[i], part);
在执行
strcpy(splitted_line[i], part);
之前不要忘记检查part
是否不是NULL
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.