2016-04-02 146 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