0

我有来自脚本的入站缓冲区数据,我需要 key => 'value' 以便我可以针对它运行数学方程(是的,我知道我需要转换为 int)。由于我确定数据是字符串,因此我尝试对其进行模式匹配。我看到了入站数据,但我从来没有得到一个肯定的匹配。

代码:

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;
                }

        }
}

print_f() 的数据输出:

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"
    }
  }   
}

我将如何到达 ["total"] 并将 # 3 添加到其中?[“总数”]+3?

4

1 回答 1

0

您只匹配 for 的前 5 个字节buff"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);
于 2014-11-14T22:29:31.820 回答