[英]Get each word from a line in a text file
I am trying to read a txt file, and I can get the line which I want, but I can not print every words in this line one by one; 我试图读取一个txt文件,我可以得到我想要的行,但是我不能逐行打印出该行中的每个单词;
for example: the line looks like: 例如:该行看起来像:
hello world 1 2 3
and I need print them one by one which looks like: 我需要一张一张地打印它们,如下所示:
hello
world
1
2
3
I got the segmentation fault core dumped error 我得到了分段错误核心转储错误
char temp[256];
while(fgets(temp, 256, fp) != NULL) {
...
int tempLength = strlen(temp);
char *tempCopy = (char*) calloc(tempLength + 1, sizeof(char));
strncpy(temCopy, temp, tempLength); // segmentation fault core dumped here;
// works fine with temp as "name country"
name = strtok_r(tempCopy, delimiter, &context);
country = strtok_r(Null, delimiter, &context);
printf("%s\n", name);
printf("%s\n", country);
}
Can anyone help me fix the code? 谁能帮我修复代码?
Thanks! 谢谢!
While read a line from a file you can invoke the following function:
if( fgets (str, 60, fp)!=NULL ) {
puts(str);
token = strtok(str," ");
while(token != NULL)
{
printf("%s\n",token);
token = strtok(NULL," ");
}
}
Impleted with strtok()
用
strtok()
char *p;
char temp[256];
while(fgets(temp,256,fp) != NULL){
p = strtok (temp," ");
while (p != NULL)
{
printf ("%s\n",p);
p = strtok (NULL, " ");
}
}
If you see man strtok
You will found 如果看到
man strtok
您会发现
BUGS BUGS
Be cautious when using these functions.
使用这些功能时要小心。 If you do use them, note that: * These functions modify their first argument.
如果确实使用它们,请注意:*这些函数会修改其第一个参数。
* These functions cannot be used on constant strings.
* The identity of the delimiting character is lost.
* The strtok() function uses a static buffer while parsing, so it's not thread safe. Use strtok_r() if this matters to you.
Try to make changes with strtok_r()
尝试使用
strtok_r()
进行更改
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.