2016-08-07 60 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));