2014-11-14 22 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);