【发布时间】:2017-12-06 23:32:09
【问题描述】:
我正在处理需要字符串和文件操作的作业。我目前正在处理字符串操作部分,我正在尝试使用 strtok 分隔文件中的行,用逗号分隔。但是,我不确定 strtok 是如何工作的。我在看下面的代码,不太明白为什么在第二个 strtok 调用中有一个 NULL,而 NULL 甚至不是一个字符串。
我正在运行的代码:
/**************************************************** ******************* * * 目的:演示“strtok”功能的程序。 * 作者:M·J·莱斯利 * 日期:94 年 4 月 23 日 * ****************************************************** **************/
#include <stdio.h>
#include <string.h>
main()
{
/* Copy the constant into the memory
* pinted to by 'test_string' */
char test_string[50]="string to split up";
/* if 'test_string' is declared as below and the program will give a
* 'Segmentation fault' This is because test_string' is pointing
* to a constant i.e. somethin that cant be changed.
char *test_string="string to split up"; */
char *sub_string;
/* Extract first string */
printf("%s\n", strtok(test_string, " "));
/* Extract remaining
* strings */
while ( (sub_string=strtok(NULL, " ")) != NULL)
{
printf("%s\n", sub_string);
}
}
/*****************************************************************
*
* Program O/P will look like this...
*
* string
* to
* split
* up
*
*****************************************************************/
【问题讨论】:
-
有什么问题?只需阅读函数说明即可。
-
strtok和NULL将从上次调用它的位置继续 -
公平地说,
strtok()是可憎的,而且非常愚蠢。