2016-04-02 140 views
0

我使用Arduino和Open Weather Map API創建一個氣象站,但我有嚴重的麻煩來解析響應sscanf有用的東西。雙引號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?

+0

使用'%[^ \ 「]'表示 」直到我讀'\「'」 – Maikel

+0

你們有'sscanf_s'?或者Boost.Spirit是否存在Arduinos? – Maikel

+0

是'Serial.printfn(「\ r \ nfound weather =%s」),天氣;'正確?如果它不是'Serial.printfn(「\ r \ nfound weather =%s」,天氣);' ? – 12431234123412341234123

回答

2

這是example。將它翻譯成您需要的任何C-Dialect。

#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"; 
    } 
} 
+0

它也工作了,謝謝! – Arank

+0

+爲變量名稱的不錯選擇;) – tofro

0

如果Serial.printfn是一個指針,該工作如printf(功能),然後

Serial.printfn("\r\nfound weather = %s"), weather; 

是不確定的行爲,並可以打印你所看到的。 你應該使用

Serial.printfn("\r\nfound weather = %s", weather); 
+0

正好,解決了,謝謝! – Arank