我正在尝试在 C 中标记一个字符串并使用 strtok_r 将标记保存到多个变量中。据我所知,我完全按照文档使用它:
char *saveptr;
char *ticketuser = strtok_r(request, ":", &saveptr);
char *ticketservice = strtok_r(NULL, ":", &saveptr);
char *ticketkey = strtok_r(NULL, ":", &saveptr);
//And so on...
其中 'request' 是一个以冒号分隔的标记字符串。当我尝试编译时,在我分配其中一个字符串的每一行上,我都会得到“赋值使指针从整数而不进行强制转换”。由于 strtok_r 应该返回一个 char*,所以我看不出问题出在哪里。
编辑:这是我的所有代码:
#include <stdio.h>
char *add( char *request ) {
char *name = "add";
char *secret = "secret1";
char *failcode = "0:add:0";
char returncode[80];
char *saveptr;
char *username = strtok_r(request, ":", &saveptr);
char *servicename = strtok_r(NULL, ":", &saveptr);
int parameter1 = atoi(strtok_r(NULL, ":", &saveptr));
int parameter2 = atoi(strtok_r(NULL, ":", &saveptr));
int ticketlead1 = atoi(strtok_r(NULL, ":", &saveptr));
char *ticketuser = strtok_r(NULL, ":", &saveptr);
char *ticketservice = strtok_r(NULL, ":", &saveptr);
char *ticketkey = strtok_r(NULL, ":", &saveptr);
//Catch any issues with the request
if (strcmp(username,ticketuser) != 0){
printf("username did not match ticket username\n");
return failcode;
}//if
else if (strcmp(servicename,ticketservice) != 0){
printf("service name did not match ticket service name\n");
return failcode;
}//else if
else if (strcmp(secret,ticketkey) != 0){
printf("secret key did not match ticket secret key\n");
return failcode;
}//else if
//request was good, return value
else{
int val = parameter1 + parameter2;
sprintf(returncode, "1:add:%d", val);
return returncode;
}//else
}//add
int main( int argc, char **argv ) {
char *returned;
char *req = "user:serv:5:8:1:user:serv:secret1";
returned = add(req);
printf(returned);
printf("\n");
return 1;
}//main