我使用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解析这些字符串?
答案 0 :(得分:3)
这是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";
}
}
答案 1 :(得分:0)
如果Serial.printfn是一个指向像printf()那样工作的函数的指针,那么
Serial.printfn("\r\nfound weather = %s"), weather;
是未定义的行为,可能会打印您看到的内容。 你应该使用
Serial.printfn("\r\nfound weather = %s", weather);