与缓冲区数据匹配的 C++ 字符串模式

c++ string pattern matching buffer data

本文关键字:C++ 字符串 模式 缓冲区 数据      更新时间:2023-10-16

我有一个来自脚本的入站缓冲区数据,我需要键 => '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"
    }
  }   
}

我将如何到达 ["总计"] 并将 #3 添加到其中? ["总计"]+3?

您只匹配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);