c - 带双引号的 sscanf

标签 c arduino scanf double-quotes openweathermap

我正在使用 Arduino 和 Open Weather Map API创建一个气象站,但我很难将响应解析为对 sscanf 有用的东西。

这是一个响应示例:

{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"base":"cmc stations","main":{"temp":14.17,"pressure":1012,"humidity":74,"temp_min":13,"temp_max":15.8},"wind":{"speed":4.6,"deg":150},"clouds":{"all":0},"dt":1459602835,"sys":{"type":1,"id":5091,"message":0.0059,"country":"GB","sunrise":1459575095,"sunset":1459622222},"id":2643743,"name":"London","cod":200}

我想从以下位置解析天气信息(清晰):

"weather":[{"id":800,"main":"Clear",

临时信息 (14) 来自:

"main":{"temp":14.17,

这是代码,我正在使用:

if (character == '}') { // Just a delimiter
      if (strstr(response, "\"weather\":[{")) { // to confirm that the string was found
        sscanf(response, ",main\":%s,", weather);
        Serial.printfn("\r\nfound weather = %s"), weather;
      }
      else if (strstr(response, "\"main\":{\"temp\":")) { // to confirm that the string was found
        sscanf(response, "temp\":%2s,", temp);
        Serial.printfn("\r\nfound temp = %s"), temp;
      }
      memset(response, 0, sizeof(response));
      idx = 0;
    }

但是 sscanf 看起来甚至没有工作,因为它总是打印 32 字节长的整个天气/临时字符串。

found weather = ,"weather":[{"id":800,"main":"Clear","description":
found temp = ],"base":"cmc stations","main":{"temp":14.17,"pressure":1011,"humi

有人知道如何使用 sscanf 解析这些字符串吗?

最佳答案

这是一个 example .将其翻译成您需要的任何 C 方言。

#include <cstdio>
#include <cstring>
#include <iostream>

const char* haystack = "\"weather\":[{\"id\":800,\"main\":\"Clear\",";
const char* needle   = "\"main\":";

int main()
{
    std::cout << "Parsing string: '" << haystack << "'\n";

    if (const char* cursor = strstr(haystack, needle)) {
        char buffer[100];
        if (sscanf(cursor, "\"main\":\"%99[^\"]\",", buffer))
            std::cout << "Parsed string: '" << buffer << "'\n";
        else 
            std::cout << "Parsing error!\n";
    } else {
        std::cout << "Could not find '" << needle << "' in '" << haystack << "'\n";
    }
}

关于c - 带双引号的 sscanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36373870/

相关文章:

c - 使用 makefile 从 lex 文件生成 a.out

javascript - NodeJS Robotics Raspberry pi 还是 Arduino 哪个更好?

c - 使用 sscanf 从字符串中读取多个单词

c - 将 CSV 文件中的值读入变量

c - 将 scanf 和 EOF 添加到程序中

c - 特定有限整数集的高效映射

c - 使用 C 和嵌入式 SQL 在 Oracle 中选择 CLOB

c++ - 网页组装 |错误 : invalid argument '-std=c++11' not allowed with 'C/ObjC'

c++ - 正确实现 Timer1 以生成 PWM

c++ - 在函数中切换case语句不会切换C++