2015-05-16 2 views
2

В настоящее время я пишу программу, предназначенную для чтения с URL-адреса и распечатываю информацию о погоде. Опуская строки коды, которые фактически делают связь с URL, здесь есть цикл, который перебирает информацию, отображаемую на данном URL, наряду с соответствующими переменными:C программирование - sscanf для чтения аналогичных строк

FILE *f = fdopen(sockfd, "r+"); 

char line[1000]; 
int count = 0; 
int i; 
char otime[200]; 
float temp; 
int hum; 
char dir[10]; 
float speed; 
int fcastTempHi; 
int fcastTempLo; 
char wkday1[40]; 
char wkday2[20]; 
char wkday3[20]; 
char wkday4[20]; 

while(fgets(line, 1000, f) != NULL) 
{ 
    sscanf(line, "\t\t\"observation_time\":\"%[^\"]\",", otime); 
    sscanf(line, "\t\t\"temp_f\":%f\",", &temp); 
    sscanf(line, "\t\t\"relative_humidity\":\"%d\",", &hum); 
    sscanf(line, "\t\t\"wind_dir\":\"%[^\"]\",", dir); 
    sscanf(line, "\t\t\"wind_mph\":%f\",", &speed); 

    sscanf(line, "\t\t\"period\":1,"); 

} 
printf("Current Conditions\n"); 
printf("Observation time: %s\n", otime); 
printf("Temperature: %f F\n", temp); 
printf("Humidity: %d%%\n", hum); 
printf("Wind: %s %f mph\n\n", dir, speed); 
printf("Forecast\n"); 
//printf("%s:\n", wkday1); 

fclose(f); 

принимает все значения я просмотрел для присутствует в пределах отображаемого содержимого URL-адреса, но я буду включать только контент, который меня интересует; чтение из

"period":1, 
    "high": { 
    "fahrenheit":"69", 
    "celsius":"20" 
    }, 
    "low": { 
    "fahrenheit":"49", 
    "celsius":"9" 
    }, 
"weekday_short":"Sat", 
"weekday":"Saturday", 

Я пытаюсь найти строку «период»: 1, и если он будет найден, я хочу пойти на, чтобы найти «день недели»: «строка», и напечатать строку позже , К сожалению, есть еще одна линия, от которой я сканирования, который выглядит как

"period":1, 
    "icon":"nt_partlycloudy", 

и эти линии происходят гораздо быстрее, чем в период с 1, что я искал. Причина, по которой я ищу «период»: 1 в частности, а не просто сканирование для «буднего дня», потому что будний день отображается несколько раз, так как это прогноз погоды на 10 дней. Поэтому я хочу, чтобы конкретный период, в который мне нужен рабочий день (период: 1), а не другие периоды (период: 2,3,4,5,6 ... и т. Д.), Поскольку они содержат следующие будни.

Я попытался использовать инструкции if, однако это было только для того, чтобы найти два вхождения «period: 1», и после этого я не смог ничего сканировать.

Я пробовал fork, когда был найден первый экземпляр «периода»: 1, однако это не сработало (скорее всего, из-за моего отсутствия опыта и общего невежества с помощью вилки).

Чтобы оставить сообщение коротким, я исключу другие методы, которые я пробовал, но я скажу, что у меня есть программа, чтобы хотя бы признать, что есть две строки, которые читают «период»: 1, хотя я просто не уверен, как подойти к такому, чтобы я мог сканировать строки после второго экземпляра «периода»: 1 ,. Заранее благодарим за любые ответы.

Больше от источника:

{ 
    "response": { 
    "version":"0.1", 
    "termsofService":"REDACTED", 
    "features": { 
    "conditions": 1 
    , 
    "forecast10day": 1 
    } 
    } 
    , "current_observation": { 
     "image": { 
     "url":"REDACTED", 
     "title":"REDACTED", 
     "link":"REDACTED" 
     }, 
     "display_location": { 
     "full":"REDACTED", 
     "city":"REDACTED", 
     "state":"REDACTED", 
     "state_name":"REDACTED", 
     "country":"US", 
     "country_iso3166":"US", 
     "zip":"REDACTED", 
     "magic":"1", 
     "wmo":"99999", 
     "latitude":"REDACTED", 
     "longitude":"REDACTED", 
     "elevation":"REDACTED" 
     }, 
     "observation_location": { 
     "full":"REDACTED", 
     "city":"REDACTED", 
     "state":"REDACTED", 
     "country":"US", 
     "country_iso3166":"US", 
     "latitude":"REDACTED", 
     "longitude":"REDACTED", 
     "elevation":"705 ft" 
     }, 
     "estimated": { 
     }, 
     "station_id":"REDACTED", 
     "observation_time":"Last Updated on May 15, 4:17 PM PDT", 
     "observation_time_rfc822":"Fri, 15 May 2015 16:17:57 -0700", 
     "observation_epoch":"1431731877", 
     "local_time_rfc822":"Fri, 15 May 2015 16:18:17 -0700", 
     "local_epoch":"1431731897", 
     "local_tz_short":"PDT", 
     "local_tz_long":"REDACTED", 
     "local_tz_offset":"-0700", 
     "weather":"Partly Cloudy", 
     "temperature_string":"68.3 F (20.2 C)", 
     "temp_f":68.3, 
     "temp_c":20.2, 
     "relative_humidity":"53%", 
     "wind_string":"From the South at 3.2 MPH Gusting to 6.5 MPH", 
     "wind_dir":"South", 
     "wind_degrees":185, 
     "wind_mph":3.2, 
     "wind_gust_mph":"6.5", 
     "wind_kph":5.1, 
     "wind_gust_kph":"10.5", 
     "pressure_mb":"1011", 
     "pressure_in":"29.87", 
     "pressure_trend":"-", 
     "dewpoint_string":"51 F (11 C)", 
     "dewpoint_f":51, 
     "dewpoint_c":11, 
     "heat_index_string":"NA", 
     "heat_index_f":"NA", 
     "heat_index_c":"NA", 
     "windchill_string":"NA", 
     "windchill_f":"NA", 
     "windchill_c":"NA", 
     "feelslike_string":"68.3 F (20.2 C)", 
     "feelslike_f":"68.3", 
     "feelslike_c":"20.2", 
     "visibility_mi":"10.0", 
     "visibility_km":"16.1", 
     "solarradiation":"--", 
     "UV":"7","precip_1hr_string":"0.00 in (0 mm)", 
     "precip_1hr_in":"0.00", 
     "precip_1hr_metric":" 0", 
     "precip_today_string":"-999.00 in (-25375 mm)", 
     "precip_today_in":"-999.00", 
     "precip_today_metric":"--", 
     "icon":"partlycloudy", 
     "icon_url":"REDACTED", 
     "forecast_url":"REDACTED", 
     "history_url":"REDACTED", 
     "ob_url":"REDACTED", 
     "nowcast":"" 
    } 
     , 
    "forecast":{ 
     "txt_forecast": { 
     "date":"2:52 PM PDT", 
     "forecastday": [ 
     { 
     "period":0, 
     "icon":"partlycloudy", 
     "icon_url":"REDACTED", 
     "title":"Friday", 
     "fcttext":"Partly cloudy. Lows overnight in the upper 40s.", 
     "fcttext_metric":"Partly cloudy. Low 9C.", 
     "pop":"0" 
     } 
     , 
     { 
     "period":1, 
     "icon":"nt_partlycloudy", 
     "icon_url":"REDACTED", 
     "title":"Friday Night", 
     "fcttext":"Some passing clouds. Low 49F. Winds SSE at 5 to 10 mph.", 
     "fcttext_metric":"Partly cloudy. Low 9C. Winds SSE at 10 to 15 km/h.", 
     "pop":"0" 
     } 
     , 
     { 
     "period":2, 
     "icon":"partlycloudy", 
     "icon_url":"REDACTED", 
     "title":"Saturday", 
     "fcttext":"Sunshine and clouds mixed. High 76F. Winds SSW at 5 to 10 mph.", 
     "fcttext_metric":"Sunshine and clouds mixed. High 24C. Winds SSW at 10 to 15 km/h.", 
     "pop":"0" 
     } 
     , 
     { 
     "period":3, 
     "icon":"nt_partlycloudy", 
     "icon_url":"REDACTED", 
     "title":"Saturday Night", 
     "fcttext":"A few clouds from time to time. Low 49F. Winds S at 5 to 10 mph.", 
     "fcttext_metric":"Partly cloudy skies. Low 9C. Winds S at 10 to 15 km/h.", 
     "pop":"10" 
     } 
     , 
     { 
     "period":4, 
     "icon":"mostlycloudy", 
     "icon_url":"REDACTED", 
     "title":"Sunday", 
     "fcttext":"More clouds than sun. High 74F. Winds SSW at 5 to 10 mph.", 
     "fcttext_metric":"Mainly cloudy. High 23C. Winds SSW at 10 to 15 km/h.", 
     "pop":"10" 
     } 
     , 
     { 
     "period":5, 
     "icon":"nt_partlycloudy", 
     "icon_url":"REDACTED", 
     "title":"Sunday Night", 
     "fcttext":"Mostly cloudy skies early will become partly cloudy late. Low around 50F. Winds S at 5 to 10 mph.", 
     "fcttext_metric":"Mostly cloudy skies early, then partly cloudy after midnight. Low near 10C. Winds S at 10 to 15 km/h.", 
     "pop":"10" 
     } 
     , 
     { 
     "period":6, 
     "icon":"clear", 
     "icon_url":"REDACTED", 
     "title":"Monday", 
     "fcttext":"A few passing clouds, otherwise generally sunny. High 74F. Winds SSW at 10 to 15 mph.", 
     "fcttext_metric":"A few clouds early, otherwise mostly sunny. High 24C. Winds SSW at 15 to 25 km/h.", 
     "pop":"10" 
     } 
     , 
     { 
     "period":7, 
     "icon":"nt_partlycloudy", 
     "icon_url":"REDACTED", 
     "title":"Monday Night", 
     "fcttext":"Partly cloudy skies. Low around 50F. Winds S at 10 to 15 mph.", 
     "fcttext_metric":"A few clouds from time to time. Low near 10C. Winds S at 15 to 25 km/h.", 
     "pop":"10" 
     } 
     , 
     { 
     "period":8, 
     "icon":"partlycloudy", 
     "icon_url":"REDACTED", 
     "title":"Tuesday", 
     "fcttext":"Partly cloudy skies. High 74F. Winds S at 10 to 15 mph.", 
     "fcttext_metric":"Some clouds in the morning will give way to mainly sunny skies for the afternoon. High 24C. Winds S at 15 to 25 km/h.", 
     "pop":"10" 
     } 
     , 
     { 
     "period":9, 
     "icon":"nt_clear", 
     "icon_url":"REDACTED", 
     "title":"Tuesday Night", 
     "fcttext":"Clear. Low near 50F. Winds S at 10 to 15 mph.", 
     "fcttext_metric":"A mostly clear sky. Low near 10C. Winds S at 15 to 25 km/h.", 
     "pop":"10" 
     } 
     , 
     { 
     "period":10, 
     "icon":"clear", 
     "icon_url":"REDACTED", 
     "title":"Wednesday", 
     "fcttext":"Sun and a few passing clouds. High 77F. Winds SSW at 5 to 10 mph.", 
     "fcttext_metric":"Sunshine along with some cloudy intervals. High near 25C. Winds SSW at 10 to 15 km/h.", 
     "pop":"10" 
     } 
     , 
     { 
     "period":11, 
     "icon":"nt_clear", 
     "icon_url":"REDACTED", 
     "title":"Wednesday Night", 
     "fcttext":"Mainly clear skies. Low 51F. Winds S at 5 to 10 mph.", 
     "fcttext_metric":"Mainly clear skies. Low 11C. Winds S at 10 to 15 km/h.", 
     "pop":"20" 
     } 
     , 
     { 
     "period":12, 
     "icon":"partlycloudy", 
     "icon_url":"REDACTED", 
     "title":"Thursday", 
     "fcttext":"Sunshine and clouds mixed. High 77F. Winds SSW at 5 to 10 mph.", 
     "fcttext_metric":"Intervals of clouds and sunshine. High near 25C. Winds SSW at 10 to 15 km/h.", 
     "pop":"10" 
     } 
     , 
     { 
     "period":13, 
     "icon":"nt_chancetstorms", 
     "icon_url":"REDACTED", 
     "title":"Thursday Night", 
     "fcttext":"Isolated thunderstorms during the evening, then partly cloudy overnight. Low 53F. Winds S at 5 to 10 mph. Chance of rain 30%.", 
     "fcttext_metric":"Widely scattered showers or a thunderstorm early. Then partly cloudy. Low 12C. Winds S at 10 to 15 km/h. Chance of rain 30%.", 
     "pop":"30" 
     } 
     { 
     "period":14, 
     "icon":"clear", 
     "icon_url":"REDACTED", 
     "title":"Friday", 
     "fcttext":"Mostly sunny skies. High 78F. Winds SSW at 5 to 10 mph.", 
     "fcttext_metric":"Sunshine. High around 25C. Winds SSW at 10 to 15    km/h.", 
    "pop":"10" 
    } 
    , 
    { 
    "period":15, 
    "icon":"nt_clear", 
    "icon_url":"REDACTED", 
    "title":"Friday Night", 
    "fcttext":"A mostly clear sky. Low 54F. Winds S at 5 to 10 mph.", 
    "fcttext_metric":"Clear skies. Low 12C. Winds S at 10 to 15 km/h.", 
    "pop":"10" 
    } 
    , 
    { 
    "period":16, 
    "icon":"clear", 
    "icon_url":"REDACTED", 
    "title":"Saturday", 
    "fcttext":"Mainly sunny. High 81F. Winds SSW at 5 to 10 mph.", 
    "fcttext_metric":"Sunny skies. High 27C. Winds SSW at 10 to 15 km/h.", 
    "pop":"10" 
    } 
    , 
    { 
    "period":17, 
    "icon":"nt_clear", 
    "icon_url":"REDACTED", 
    "title":"Saturday Night", 
    "fcttext":"A few clouds from time to time. Low 53F. Winds S at 5 to 10 mph.", 
    "fcttext_metric":"Mostly clear skies. Low 12C. Winds S at 10 to 15 km/h.", 
    "pop":"10" 
    } 
    , 
    { 
    "period":18, 
    "icon":"clear", 
    "icon_url":"REDACTED", 
    "title":"Sunday", 
    "fcttext":"Mostly sunny skies. High 82F. Winds SSW at 5 to 10 mph.", 
    "fcttext_metric":"A few clouds from time to time. High 28C. Winds SSW at 10 to 15 km/h.", 
    "pop":"10" 
    } 
    , 
    { 
    "period":19, 
    "icon":"nt_clear", 
    "icon_url":"REDACTED", 
    "title":"Sunday Night", 
    "fcttext":"Mostly clear. Low 53F. Winds SSE at 5 to 10 mph.", 
    "fcttext_metric":"A mostly clear sky. Low 12C. Winds SSE at 10 to 15 km/h.", 
    "pop":"10" 
    } 
     ] 
     }, 
     "simpleforecast": { 
     "forecastday": [ 
     {"date":{ 
    "epoch":"1431741600", 
    "pretty":"7:00 PM PDT on May 15, 2015", 
    "day":15, 
    "month":5, 
    "year":2015, 
    "yday":134, 
    "hour":19, 
    "min":"00", 
    "sec":0, 
    "isdst":"1", 
    "monthname":"May", 
    "monthname_short":"May", 
    "weekday_short":"Fri", 
    "weekday":"Friday", 
    "ampm":"PM", 
    "tz_short":"PDT", 
    "tz_long":"REDACTED" 
}, 
     "period":1, 
     "high": { 
     "fahrenheit":"69", 
     "celsius":"20" 
     }, 
     "low": { 
     "fahrenheit":"49", 
     "celsius":"9" 
     }, 
     "conditions":"Partly Cloudy", 
     "icon":"partlycloudy", 
     "icon_url":"REDACTED", 
     "skyicon":"", 
     "pop":0, 
     "qpf_allday": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_day": { 
     "in": null, 
     "mm": null 
     }, 
     "qpf_night": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "snow_allday": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_day": { 
     "in": null, 
     "cm": null 
     }, 
     "snow_night": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "maxwind": { 
     "mph": 8, 
     "kph": 13, 
     "dir": "", 
     "degrees": 0 
     }, 
     "avewind": { 
     "mph": 1, 
     "kph": 2, 
     "dir": "South", 
     "degrees": 186 
     }, 
     "avehumidity": 73, 
     "maxhumidity": 0, 
     "minhumidity": 0 
     } 
     , 
     {"date":{ 
    "epoch":"1431828000", 
    "pretty":"7:00 PM PDT on May 16, 2015", 
    "day":16, 
    "month":5, 
    "year":2015, 
    "yday":135, 
    "hour":19, 
    "min":"00", 
    "sec":0, 
    "isdst":"1", 
    "monthname":"May", 
    "monthname_short":"May", 
    "weekday_short":"Sat", 
    "weekday":"Saturday", 
    "ampm":"PM", 
    "tz_short":"PDT", 
    "tz_long":"REDACTED" 
}, 
     "period":2, 
     "high": { 
     "fahrenheit":"76", 
     "celsius":"24" 
     }, 
     "low": { 
     "fahrenheit":"49", 
     "celsius":"9" 
     }, 
     "conditions":"Partly Cloudy", 
     "icon":"partlycloudy", 
     "icon_url":"REDACTED", 
     "skyicon":"", 
     "pop":0, 
     "qpf_allday": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_day": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_night": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "snow_allday": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_day": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_night": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "maxwind": { 
     "mph": 10, 
     "kph": 16, 
     "dir": "SSW", 
     "degrees": 196 
     }, 
     "avewind": { 
     "mph": 8, 
     "kph": 13, 
     "dir": "SSW", 
     "degrees": 196 
     }, 
     "avehumidity": 54, 
     "maxhumidity": 0, 
     "minhumidity": 0 
     } 
     , 
     {"date":{ 
    "epoch":"1431914400", 
    "pretty":"7:00 PM PDT on May 17, 2015", 
    "day":17, 
    "month":5, 
    "year":2015, 
    "yday":136, 
    "hour":19, 
    "min":"00", 
    "sec":0, 
    "isdst":"1", 
    "monthname":"May", 
    "monthname_short":"May", 
    "weekday_short":"Sun", 
    "weekday":"Sunday", 
    "ampm":"PM", 
    "tz_short":"PDT", 
    "tz_long":"REDACTED" 
}, 
     "period":3, 
     "high": { 
     "fahrenheit":"74", 
     "celsius":"23" 
     }, 
     "low": { 
     "fahrenheit":"50", 
     "celsius":"10" 
     }, 
     "conditions":"Mostly Cloudy", 
     "icon":"mostlycloudy", 
     "icon_url":"REDACTED", 
     "skyicon":"", 
     "pop":10, 
     "qpf_allday": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_day": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_night": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "snow_allday": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_day": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_night": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "maxwind": { 
     "mph": 10, 
     "kph": 16, 
     "dir": "SSW", 
     "degrees": 192 
     }, 
     "avewind": { 
     "mph": 9, 
     "kph": 14, 
     "dir": "SSW", 
     "degrees": 192 
     }, 
     "avehumidity": 54, 
     "maxhumidity": 0, 
     "minhumidity": 0 
     } 
     , 
     {"date":{ 
    "epoch":"1432000800", 
    "pretty":"7:00 PM PDT on May 18, 2015", 
    "day":18, 
    "month":5, 
    "year":2015, 
    "yday":137, 
    "hour":19, 
    "min":"00", 
    "sec":0, 
    "isdst":"1", 
    "monthname":"May", 
    "monthname_short":"May", 
    "weekday_short":"Mon", 
    "weekday":"Monday", 
    "ampm":"PM", 
    "tz_short":"PDT", 
    "tz_long":"REDACTE" 
}, 
     "period":4, 
     "high": { 
     "fahrenheit":"74", 
     "celsius":"23" 
     }, 
     "low": { 
     "fahrenheit":"50", 
     "celsius":"10" 
     }, 
     "conditions":"Clear", 
     "icon":"clear", 
     "icon_url":"REDACTED", 
     "skyicon":"", 
     "pop":10, 
     "qpf_allday": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_day": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_night": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "snow_allday": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_day": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_night": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "maxwind": { 
     "mph": 15, 
     "kph": 24, 
     "dir": "SSW", 
     "degrees": 209 
     }, 
     "avewind": { 
     "mph": 10, 
     "kph": 16, 
     "dir": "SSW", 
     "degrees": 209 
     }, 
     "avehumidity": 52, 
     "maxhumidity": 0, 
     "minhumidity": 0 
     } 
     , 
     {"date":{ 
    "epoch":"1432087200", 
    "pretty":"7:00 PM PDT on May 19, 2015", 
    "day":19, 
    "month":5, 
    "year":2015, 
    "yday":138, 
    "hour":19, 
    "min":"00", 
    "sec":0, 
    "isdst":"1", 
    "monthname":"May", 
    "monthname_short":"May", 
    "weekday_short":"Tue", 
    "weekday":"Tuesday", 
    "ampm":"PM", 
    "tz_short":"PDT", 
    "tz_long":"REDACTED" 
}, 
     "period":5, 
     "high": { 
     "fahrenheit":"74", 
     "celsius":"23" 
     }, 
     "low": { 
     "fahrenheit":"50", 
     "celsius":"10" 
     }, 
     "conditions":"Partly Cloudy", 
     "icon":"partlycloudy", 
     "icon_url":"REDACTED", 
     "skyicon":"", 
     "pop":10, 
     "qpf_allday": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_day": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_night": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "snow_allday": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_day": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_night": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "maxwind": { 
     "mph": 15, 
     "kph": 24, 
     "dir": "S", 
     "degrees": 190 
     }, 
     "avewind": { 
     "mph": 10, 
     "kph": 16, 
     "dir": "S", 
     "degrees": 190 
     }, 
     "avehumidity": 55, 
     "maxhumidity": 0, 
     "minhumidity": 0 
     } 
     , 
     {"date":{ 
    "epoch":"1432173600", 
    "pretty":"7:00 PM PDT on May 20, 2015", 
    "day":20, 
    "month":5, 
    "year":2015, 
    "yday":139, 
    "hour":19, 
    "min":"00", 
    "sec":0, 
    "isdst":"1", 
    "monthname":"May", 
    "monthname_short":"May", 
    "weekday_short":"Wed", 
    "weekday":"Wednesday", 
    "ampm":"PM", 
    "tz_short":"PDT", 
    "tz_long":"REDACTED" 
}, 
     "period":6, 
     "high": { 
     "fahrenheit":"77", 
     "celsius":"25" 
     }, 
     "low": { 
     "fahrenheit":"51", 
     "celsius":"11" 
     }, 
     "conditions":"Clear", 
     "icon":"clear", 
     "icon_url":"REDACTED", 
     "skyicon":"", 
     "pop":10, 
     "qpf_allday": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_day": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_night": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "snow_allday": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_day": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_night": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "maxwind": { 
     "mph": 10, 
     "kph": 16, 
     "dir": "SSW", 
     "degrees": 196 
     }, 
     "avewind": { 
     "mph": 9, 
     "kph": 14, 
     "dir": "SSW", 
     "degrees": 196 
     }, 
     "avehumidity": 54, 
     "maxhumidity": 0, 
     "minhumidity": 0 
     } 
     , 
     {"date":{ 
    "epoch":"1432260000", 
    "pretty":"7:00 PM PDT on May 21, 2015", 
    "day":21, 
    "month":5, 
    "year":2015, 
    "yday":140, 
    "hour":19, 
    "min":"00", 
    "sec":0, 
    "isdst":"1", 
    "monthname":"May", 
    "monthname_short":"May", 
    "weekday_short":"Thu", 
    "weekday":"Thursday", 
    "ampm":"PM", 
    "tz_short":"PDT", 
    "tz_long":"REDACTED" 
}, 
     "period":7, 
     "high": { 
     "fahrenheit":"77", 
     "celsius":"25" 
     }, 
     "low": { 
     "fahrenheit":"53", 
     "celsius":"12" 
     }, 
     "conditions":"Partly Cloudy", 
     "icon":"partlycloudy", 
     "icon_url":"REDACTED", 
     "skyicon":"", 
     "pop":10, 
     "qpf_allday": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_day": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_night": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "snow_allday": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_day": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_night": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "maxwind": { 
     "mph": 10, 
     "kph": 16, 
     "dir": "SSW", 
     "degrees": 195 
     }, 
     "avewind": { 
     "mph": 8, 
     "kph": 13, 
     "dir": "SSW", 
     "degrees": 195 
     }, 
     "avehumidity": 53, 
     "maxhumidity": 0, 
     "minhumidity": 0 
     } 
     , 
     {"date":{ 
    "epoch":"1432346400", 
    "pretty":"7:00 PM PDT on May 22, 2015", 
    "day":22, 
    "month":5, 
    "year":2015, 
    "yday":141, 
    "hour":19, 
    "min":"00", 
    "sec":0, 
    "isdst":"1", 
    "monthname":"May", 
    "monthname_short":"May", 
    "weekday_short":"Fri", 
    "weekday":"Friday", 
    "ampm":"PM", 
    "tz_short":"PDT", 
    "tz_long":"REDACTED" 
}, 
     "period":8, 
     "high": { 
     "fahrenheit":"78", 
     "celsius":"26" 
     }, 
     "low": { 
     "fahrenheit":"54", 
     "celsius":"12" 
     }, 
     "conditions":"Clear", 
     "icon":"clear", 
     "icon_url":"REDACTED", 
     "skyicon":"", 
     "pop":10, 
     "qpf_allday": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_day": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_night": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "snow_allday": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_day": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_night": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "maxwind": { 
     "mph": 10, 
     "kph": 16, 
     "dir": "SSW", 
     "degrees": 208 
     }, 
     "avewind": { 
     "mph": 8, 
     "kph": 13, 
     "dir": "SSW", 
     "degrees": 208 
     }, 
     "avehumidity": 59, 
     "maxhumidity": 0, 
     "minhumidity": 0 
     } 
     , 
     {"date":{ 
    "epoch":"1432432800", 
    "pretty":"7:00 PM PDT on May 23, 2015", 
    "day":23, 
    "month":5, 
    "year":2015, 
    "yday":142, 
    "hour":19, 
    "min":"00", 
    "sec":0, 
    "isdst":"1", 
    "monthname":"May", 
    "monthname_short":"May", 
    "weekday_short":"Sat", 
    "weekday":"Saturday", 
    "ampm":"PM", 
    "tz_short":"PDT", 
    "tz_long":"REDACTED" 
}, 
     "period":9, 
     "high": { 
     "fahrenheit":"81", 
     "celsius":"27" 
     }, 
     "low": { 
     "fahrenheit":"53", 
     "celsius":"12" 
     }, 
     "conditions":"Clear", 
     "icon":"clear", 
     "icon_url":"REDACTED", 
     "skyicon":"", 
     "pop":10, 
     "qpf_allday": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_day": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_night": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "snow_allday": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_day": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_night": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "maxwind": { 
     "mph": 10, 
     "kph": 16, 
     "dir": "SSW", 
     "degrees": 202 
     }, 
     "avewind": { 
     "mph": 9, 
     "kph": 14, 
     "dir": "SSW", 
     "degrees": 202 
     }, 
     "avehumidity": 57, 
     "maxhumidity": 0, 
     "minhumidity": 0 
     } 
     , 
     {"date":{ 
    "epoch":"1432519200", 
    "pretty":"7:00 PM PDT on May 24, 2015", 
    "day":24, 
    "month":5, 
    "year":2015, 
    "yday":143, 
    "hour":19, 
    "min":"00", 
    "sec":0, 
    "isdst":"1", 
    "monthname":"May", 
    "monthname_short":"May", 
    "weekday_short":"Sun", 
    "weekday":"Sunday", 
    "ampm":"PM", 
    "tz_short":"PDT", 
    "tz_long":"REDACTED" 
}, 
     "period":10, 
     "high": { 
     "fahrenheit":"82", 
     "celsius":"28" 
     }, 
     "low": { 
     "fahrenheit":"53", 
     "celsius":"12" 
     }, 
     "conditions":"Clear", 
     "icon":"clear", 
     "icon_url":"REDACTED", 
     "skyicon":"", 
     "pop":10, 
     "qpf_allday": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_day": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "qpf_night": { 
     "in": 0.00, 
     "mm": 0 
     }, 
     "snow_allday": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_day": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "snow_night": { 
     "in": 0.0, 
     "cm": 0.0 
     }, 
     "maxwind": { 
     "mph": 10, 
     "kph": 16, 
     "dir": "SSW", 
     "degrees": 206 
     }, 
     "avewind": { 
     "mph": 9, 
     "kph": 14, 
     "dir": "SSW", 
     "degrees": 206 
     }, 
     "avehumidity": 55, 
     "maxhumidity": 0, 
     "minhumidity": 0 
     } 
     ] 
     } 
    } 
} 

Я обновил со всеми данными из источника.

+0

Было бы проще сделать 'char * rightSide = strchr (line, ':')' и проанализировать значение в 'rightSide + 1'. –

+0

Я вижу, что вы говорите, однако есть еще два (или более) экземпляра, в которых 1 будет происходить с правой стороны: – JavaFuntimeEngine

+0

Можете ли вы разместить больше входного файла? –

ответ

1

Из чего я могу понять, вы пытаетесь проверить, есть ли два экземпляра "period": 1, а если есть, прочитайте другое значение. В этом случае, я считаю, что-то, как это должно работать:

#include <stdio.h> 
#include <stdbool.h> 

int main() 
{ 
    // I stored the data in weather.txt, you'll have to change this 
    FILE *f = fopen("weather.txt", "r+"); 

    char line[1000]; 
    int count = 0; 
    int i; 
    char otime[200]; 
    float temp; 
    int hum; 
    char dir[10]; 
    float speed; 
    int fcastTempHi; 
    int fcastTempLo; 
    char wkday1[40]; 
    char wkday2[20]; 
    char wkday3[20]; 
    char wkday4[20]; 

    int period1 = 0;  // Keep track of how many period: 1's we've seen 
    int value = 0;   // Temp variable to store value 
    bool haswkday = false; // Bool for if we've gotten the value or not 

    while(fgets(line, 1000, f) != NULL) 
    { 
     sscanf(line, "\t\t\"observation_time\":\"%[^\"]\",", otime); 
     sscanf(line, "\t\t\"temp_f\":%f\",", &temp); 
     sscanf(line, "\t\t\"relative_humidity\":\"%d\",", &hum); 
     sscanf(line, "\t\t\"wind_dir\":\"%[^\"]\",", dir); 
     sscanf(line, "\t\t\"wind_mph\":%f\",", &speed); 

     // If period is scanned successfully and its value is 1 
     if (sscanf(line, "\t\t\"period\":%d,", &value) != 0 && value == 1) 
     { 
     period1++; // Increase how many times we've seen it 
     } 

     // If we've seen exactly 2 period: 1's, then also check for weekday 
     if (period1 == 2 && sscanf(line, "\t\t\"weekday\":\"%[^\"]\"", &wkday1) > 0) 
     { 
     haswkday = true; // Weekday value already stored, say that we've gotten it 
     } 
    } 
    printf("Current Conditions\n"); 
    printf("Observation time: %s\n", otime); 
    printf("Temperature: %f F\n", temp); 
    printf("Humidity: %d%%\n", hum); 
    printf("Wind: %s %f mph\n\n", dir, speed); 
    printf("Forecast\n"); 

    // If we got the value, then print it 
    if (haswkday) 
    { 
    printf("%s:\n", wkday1); 
    } 

    fclose(f); 
} 
+0

Это умный подход к проблеме. Я был очень хорошо знаком с booleans из java, однако тема не была даже рассмотрена в моем классе C, и я даже не думал использовать ее. Этот метод будет распечатывать день недели просто отлично (тогда как я получаю только случайные символы), однако, похоже, на следующий день. Значение печати должно быть прочитано в субботу (с учетом сегодняшней даты), но вместо этого печатает в воскресенье. Я работаю с ним, хотя в настоящее время, но я думал, что дам вам несколько отзывов. Если я найду способ заставить его напечатать истинный день, я отвечу. Спасибо за ваш вклад. – JavaFuntimeEngine

+0

@JavaFuntimeEngine Вы получаете воскресенье с точным кодом, который я разместил? Возможно, вы можете опубликовать данные, которые дают неправильный вывод, и я могу взглянуть на него. У меня нет данных о «буднем»: «воскресенье». – ozdrgnaDiies

+0

Данные содержат два раздела «периодов» от 0 до 19 и от 1 до 10. Я отключил данные в «периоде»: 2 (в интересах того, чтобы страница не была невероятно заполнена текстом), которая имела бы была информация «будний день»: «воскресенье», прилагаемая к ней. Точно так же будет период 3 с его усиливающими данными и «будним днем»: «понедельник» и т. Д. До 10-го периода. Я отредактирую текущий текст, чтобы отразить это. – JavaFuntimeEngine

0

Хорошо, благодаря ozdrgnaDiies, я нашел это решение. Все, что было добавлено к его решению, было просто увеличивать период1 после того, как был найден экземпляр wkday1, чтобы он больше не увеличивался до тех пор, пока не будут покрыты все периоды.

FILE *f = fdopen(sockfd, "r+"); 

char line[1000]; 
char otime[200]; 
float temp; 
int hum; 
char dir[10]; 
float speed; 
int fcastTempHi; 
int fcastTempLo; 
char wkday1[40]; 
char wkday2[20]; 
char wkday3[20]; 
char wkday4[20]; 

int period1 = 0;  // Keep track of how many period: 1's we've seen 
int value = 0;   // Temp variable to store value 
bool haswkday = false; // Bool for if we've gotten the value or not 
while(fgets(line, 1000, f) != NULL)// fgets returns NULL, whereas fscanf returns EOF 
{ 
    sscanf(line, "\t\t\"observation_time\":\"%[^\"]\",", otime); 
    sscanf(line, "\t\t\"temp_f\":%f\",", &temp); 
    sscanf(line, "\t\t\"relative_humidity\":\"%d\",", &hum); 
    sscanf(line, "\t\t\"wind_dir\":\"%[^\"]\",", dir); 
    sscanf(line, "\t\t\"wind_mph\":%f\",", &speed); 

    // If period is scanned successfully and its value is 1 
    if(sscanf(line, "\t\t\"period\":%d,", &value) != 0 && value == 1) 
    { 
     period1++; // Increase how many times we've seen it 
    } 

    // If we've seen exactly 2 period: 1's, then also check for weekday 
    if(period1 == 2 && sscanf(line, "\t\"weekday\":\"%[^\"]\"", wkday1) > 0) 
    { 
     haswkday = true; // Weekday value already stored, say that we've gotten it 

     period1++; 
    }  
} 
printf("Current Conditions\n"); 
printf("Observation time: %s\n", otime); 
printf("Temperature: %f F\n", temp); 
printf("Humidity: %d%%\n", hum); 
printf("Wind: %s %f mph\n\n", dir, speed); 
printf("Forecast\n"); 
// If we got the value, then print it 
if(haswkday) 
{ 
    printf("%s:\n", wkday1); 
} 

fclose(f); 

Это успешно распечатает день недели, следующий за текущим днем. Еще раз спасибо.

Смежные вопросы