2014-11-14 65 views
0

我有一個腳本的入站緩衝區數據,我需要key =>'value'以便我可以對它運行一個數學方程(是的,我知道我需要轉換爲int) 。由於我確定數據是字符串,我試圖對它進行模式匹配。 我看到入站數據,但我從未得到正面匹配。C++字符串模式匹配緩衝區數據

代碼:從print_f輸出

int getmyData() 
{ 

     char key[] = "total"; 
     char buff[BUFSIZ]; 
     FILE *fp = popen("php getMyorders.php 155", "r"); 
     while (fgets(buff, BUFSIZ, fp)){ 
       printf("%s", buff); 
       //if (strstr(key, buff) == buff) { 
       if (!memcmp(key, buff, sizeof(key) - 1)) { 
         std::cout << "Match "<< std::endl; 
       } 

     } 
} 

數據():

array(2) { 
    ["success"]=> 
    string(1) "1" 
    ["return"]=> 
    array(3) { 
    [0]=> 
    array(7) { 
     ["orderid"]=> 
     string(9) "198397652" 
     ["created"]=> 
     string(19) "2014-11-14 15:10:10" 
     ["ordertype"]=> 
     string(3) "Buy" 
     ["price"]=> 
     string(10) "0.00517290" 
     ["quantity"]=> 
     string(10) "0.00100000" 
     ["orig_quantity"]=> 
     string(10) "0.00100000" 
     ["total"]=> 
     string(10) "0.00000517" 
    } 
    [1]=> 
    array(7) { 
     ["orderid"]=> 
     string(9) "198397685" 
     ["created"]=> 
     string(19) "2014-11-14 15:10:13" 
     ["ordertype"]=> 
     string(3) "Buy" 
     ["price"]=> 
     string(10) "0.00517290" 
     ["quantity"]=> 
     string(10) "0.00100000" 
     ["orig_quantity"]=> 
     string(10) "0.00100000" 
     ["total"]=> 
     string(10) "0.00000517" 
    } 
    [2]=> 
    array(7) { 
     ["orderid"]=> 
     string(9) "198398295" 
     ["created"]=> 
     string(19) "2014-11-14 15:11:14" 
     ["ordertype"]=> 
     string(3) "Buy" 
     ["price"]=> 
     string(10) "0.00517290" 
     ["quantity"]=> 
     string(10) "0.00100000" 
     ["orig_quantity"]=> 
     string(10) "0.00100000" 
     ["total"]=> 
     string(10) "0.00000517" 
    } 
    } 
} 

我怎麼會去[ 「總」]和#3補充呢? [ 「總」] + 3?

+0

你能否詳細說明世界衛生大會這個'['total'] + 3'的意思是。 – sln 2014-11-14 22:47:18

回答

0

你只是匹配buff的前5個字節爲"total",而不是實際搜索。如果你的緩衝區不包含任何空值,你要使用的功能是strstr

while (fgets(buff, BUFSIZ, fp)) { 
    const char* total = strstr(buff, key); 
    if (total) { 
     // found our total, which should point 
     // ["total"] => 
     // ^
     // here 
    } 
} 

如果你的緩衝區可以包含空值,那麼你需要寫一個將被稱爲memstr功能,這是相當簡單:只是嘗試在每一點上找到它:

const char* memstr(const char* str, size_t str_size, 
        const char* target, size_t target_size) { 

    for (size_t i = 0; i != str_size - target_size; ++i) { 
     if (!memcmp(str + i, target, target_size)) { 
      return str + i; 
     } 
    } 

    return NULL; 
} 

它在你的情況用法是:

const char* total = memstr(buff, BUFSIZ, key, sizeof(key) - 1);