0

私は 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 を使用してこれらの文字列を解析する方法を知っている人はいますか?

4

2 に答える 2

4

ここにがあります。必要な 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";
    }
}
于 2016-04-02T14:01:17.427 に答える