【发布时间】:2015-04-28 02:44:48
【问题描述】:
我正在尝试根据 \r\n 分隔符在 C 中标记一个字符串,并希望在后续调用 strtok() 后打印出每个字符串。在我拥有的while 循环中,对每个令牌都进行了处理。
当我包含处理代码时,我收到的唯一输出是第一个令牌,但是当我取出处理代码时,我收到了每个令牌。这对我来说没有意义,我想知道我做错了什么。
代码如下:
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int c = 0, c2 = 0;
char *tk, *tk2, *tk3, *tk4;
char buf[1024], buf2[1024], buf3[1024];
char host[1024], path[1024], file[1024];
strcpy(buf, "GET /~yourloginid/index.htm HTTP/1.1\r\nHost: remote.cba.csuohio.edu\r\n\r\n");
tk = strtok(buf, "\r\n");
while(tk != NULL)
{
printf("%s\n", tk);
/*
if(c == 0)
{
strcpy(buf2, tk);
tk2 = strtok(buf2, "/");
while(tk2 != NULL)
{
if(c2 == 1)
strcpy(path, tk2);
else if(c2 == 2)
{
tk3 = strtok(tk2, " ");
strcpy(file, tk3);
}
++c2;
tk2 = strtok(NULL, "/");
}
}
else if(c == 1)
{
tk3 = strtok(tk, " ");
while(tk3 != NULL)
{
if(c2 == 1)
{
printf("%s\n", tk3);
// strcpy(host, tk2);
// printf("%s\n", host);
}
++c2;
tk3 = strtok(NULL, " ");
}
}
*/
++c;
tk = strtok(NULL, "\r\n");
}
return 0;
}
如果没有那些 if else 语句,我会收到以下输出...
GET /~yourloginid/index.htm HTTP/1.1
Host: remote.cba.csuohio.edu
...但是,通过这些 if else 声明,我收到了这个...
GET /~yourloginid/index.htm HTTP/1.1
不知道为什么我看不到另一个token,因为程序结束了,这意味着循环必须一直发生到整个字符串的结尾,对吧?
【问题讨论】:
-
考虑
strtok必须保留外部枚举的位置上下文。提示:check the docs。现在考虑那些 innerstrtok调用对隐藏的上下文做了什么。strtok_s或 POSIXstrtok_r之类的替代方案可能会减轻您的麻烦。