2012-08-14 100 views
0

這是我用cgi檢索html數據的C++代碼。從cgi POST數據獲取輸入

char* fileContentLength; 
int nContentLength; 
fileContentLength = getenv("CONTENT_LENGTH"); 

if(fileContentLength == NULL) 
    return -1;  

nContentLength = atoi(fileContentLength); 

if(nContentLength == 0) 
    return -1; 

data = (char*) malloc(nContentLength+1); 

if(data == NULL)  
    return -1; 

memset(data, 0, nContentLength+1); 
if(fread(data, 1, nContentLength, stdin) == 0) 
    return -1; 

if(ferror(stdin)) 

執行此代碼後,我得到了下面的結果變量「數據」。

F0 = fname0 & L0 = lname0 & F1 = fname1 & L1 = lname1 & F2 = fname2 & L2 = lname2 & F3 = & L3 =

此處F0,L0,F1,L1是HTML頁面的輸入框的名稱。從這個字符串我需要分開像fname0,lname0,fname1,lname1等值。我使用sscanf函數。但我無法檢索正確的結果。我如何將上述字符串的值分配給名爲firstname和lastname的局部變量。

回答

3

查看例如功能strtok。在循環中使用它來拆分'&'以獲取所有鍵值對(例如)。然後在'='字符處查看向量分割每個字符串(您可以在這裏再次使用strtok)。您可以將鍵和值放在std::map中,或直接使用。

對於更多的特定於C++的方法,請使用std::string::findstd::string::substr而不是strtok。然後,您可以將鍵和值直接放入映射中,而不是將它們臨時存儲爲向量中的字符串。

編輯:如何獲得最後一對

的最後一個鍵 - 值對不被'&'字符終止,所以你必須循環後檢查的最後一對。這可以通過獲取字符串的副本來完成,然後在最後一個'&'之後獲取子字符串。像這樣的事情也許:

char *copy = strdup(data); 

// Loop getting key-value pairs using `strtok` 
// ... 

// Find the last '&' in the string 
char *last_amp_pos = strrchr(copy, '&'); 
if (last_amp_pos != NULL && last_amp_pos < (copy + strlen(copy))) 
{ 
    last_amp_pos++; // Increase to point to first character after the ampersand 

    // `last_amp_pos` now points to the last key-value pair 
} 

// Must be free'd since we allocated a copy above 
free(copy); 

我們需要使用字符串的副本,如果因爲strtok修改字符串的原因。

我仍然會推薦你使用C++字符串,而不是依靠舊的C函數。它可能會簡化一切,包括您不需要爲最後一個鍵值對添加額外的檢查。

+0

獲取最後一個空元素(f3和l3)的值有個問題。我需要知道元素的值是否爲空。但我不能這樣做使用strtok函數。 – 2012-08-25 11:34:13

+0

@SmithDwayne更新了我的答案,包括如何獲得最後一對。 – 2012-08-27 07:20:54