2016-08-07 55 views
-2

如何解析此字符串GET /STA/ID=HelloWorld/Pass=Testin123 HTTP/1.1首先,我需要检查STA,如果存在,请继续扫描字符串。放ID值在这种情况下HelloWorld应该是char数据类型SSIDPass值存储,在这种情况下Testin123应该是char数据类型的商店Pass解析HTTP字符串

它首先要确定的STA字符串的存在。如果它不存在,请不要进入循环。如果退出,请搜索IDPass。存储它。

现在的问题是我无法存储值IDpass。也无法搜索STA

char GetString[] = "GET /STA/ID=Test/Pass=123 HTTP/1.1"; 

char *get = strtok(GetString, " "); 
char *request = strtok(NULL, " "); 
char *rtype = strtok(NULL, " "); 
char *FirstPart; 

int main() 
{ 
if (request != NULL) 
{ 
    FirstPart = strtok(request,"/"); 
    while(FirstPart) 
    { 
    if (!strncmp(part, "STA")) 
     { 
     //Print STA Found 

      if(!strncmp(part, "ID=", 3)) 
      { 
       //Store value of ID 
      } 

      if(!strncmp(part, "Pass=", 5)) 
      { 
      //Store the Pass 
      } 
      } 
     } 
     FirstPart =strtok(NULL,'/'); 
    } 
} 
+0

这是一个奇怪的地方停下来,你得到了令牌化的权利,但没有测试与strcmp字符串相等吗? – covener

+0

@covener我已添加完整的代码。 –

+2

问题是,小错误隐藏你的重大错误。有一个无效的调用strncmp,没有长度参数。有一个无效的调用strtok与字符第二个参数,应该是一个字符串。你的while循环遍历令牌,但是如果该令牌是“STA”,则只做任何事情,但如果它是它,则检查它是否是别的东西,但是你知道它是“STA”,所以其他if子句永远不会匹配。 – MAP

回答

1

需要一点清理。一个提示:使用编译器切换所有警告和错误,它们存在是有原因的。你的代码甚至没有编译,这是最简单的条件。

但无论如何:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main() 
{ 
    char GetString[] = "GET /STA/ID=Test/Pass=123 HTTP/1.1"; 
    // you cannot do it globally in that way, so I pulled it all into main() 
    char *request, *FirstPart; 
    // please don't use all upper-case for normal variables 
    // I did it for some clarity here 
    char *ID, *PASS; 

    // skip "GET" 
    strtok(GetString, " "); 
    // get first part 
    request = strtok(NULL, " "); 

    if (request != NULL) { 
    FirstPart = strtok(request, "/"); 
    // check for base condition 
    if (!strncmp(FirstPart, "STA", 3)) { 
     //Print STA Found 
     printf("STA = %s\n", FirstPart); 
    } else { 
     fprintf(stderr, "STA not found!\n"); 
     exit(EXIT_FAILURE); 
    } 
    FirstPart = strtok(NULL, "/"); 
    // graze the key-value combinations 
    while (FirstPart) { 
     // We check them all here, one after the other 
     if (!strncmp(FirstPart, "ID=", 3)) { 
    //Store value of ID 
    ID = strchr(FirstPart, '='); 
    // ID is now "=Test", so skip '=' 
    ID++; 
    printf("ID = %s, value of ID = %s\n", FirstPart, ID); 
     } else if (!strncmp(FirstPart, "Pass=", 5)) { 
    //Store the Pass 
    PASS = strchr(FirstPart, '='); 
    // PASS is now "=123", so skip '=' 
    PASS++; 
    printf("PASS = %s, value of PASS = %s\n", FirstPart, PASS); 
     } else { 
    printf("Unknown part \"%s\", ignoring\n", FirstPart); 
     } 
     FirstPart = strtok(NULL, "/"); 
    } 
    } else { 
    fprintf(stderr, "No input at all\n"); 
    exit(EXIT_FAILURE); 
    } 
    exit(EXIT_SUCCESS); 
} 

指针IDPASS点只空终止值,它们不是独立的内存。您可以使用malloc()来获得一些数字,并使用strlen()来衡量金额。以ID为例:ptr_to_mem_for_ID = malloc(strlen(ID));