下面是我在 codeblocks 版本 13:12 中的代码。它没有评论,因为我很快放下它在这里问我失去了我的头发!我担心的是,我希望我的 char *
目标是 /cat.html?name=image
但我只得到 /cat.html
!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
const char *space = " ";
const char *marker = "?";
const char line[] = { "GET /cat.html?name=image HTTP/1.1" };
int n = strlen(line), i, j, k, a;
char string[n + 1];
for (i = 0; i <= n; i++) {
string[i] = line[i];
string[n] = '\0';
}
printf(" line has %i characters \n\n", n);
char *method = strtok(string, space);
char *target = strtok(NULL, space);
char *version = strtok(NULL, space);
char *abs_path = strtok(target, marker);
char *query = strtok(NULL, marker);
printf("\n line is:%s \n"
"\n method is:%s \n"
"\n target is:%s \n"
"\n version is:%s \n"
"\n abs_path is:%s \n"
"\n query is:%s \n\n\n",
line, method, target, version, abs_path, query);
int l = strlen(target);
if (strcmp(method, "GET") != 0) {
printf("wrong method error 405 \n\n");
}
printf(" target contains %i characters \n\n", l);
for (j = 0; j <= l; j++) {
if (target[0] != '/') {
printf("wrong target does not start with \\/error 501\n\n");
}
if (target[j] == '"') {
printf("wrong target error 400 has a \" \n\n");
}
}
if (strchr(abs_path, '.') == NULL) {
printf("wrong absolute path has no \. \n\n");
}
if (strncmp(version, "HTTP/1.1", 8) != 0) {
printf("wrong version not HTTP/1.1 error 505 \n\n");
}
return 0;
}
最佳答案
char * method = strtok(string, space);
char * target = strtok(NULL, space);
char * version = strtok(NULL, space);
在这些行之后,target
确实确实具有值 "/cat.html?name=image"
。问题是您随后在 target
上再次调用 strtok,这将修改字符串:
abs_path = strtok(target, marker);
在该行之后,target
将具有值 "/cat.html"
如果您想保留 target
的原始值,您需要在第二个 strtok
之前复制它。在目标
上。
关于c - 为什么 strtok() 不从行中选择 '?' 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41090434/