#include <stdlib.h>
void printLine(char* line) {
char lat, lon;
unsigned int year, month, day;
float temp, uncertainty, latitude, longitude;
char country[100], city[100];
int result;
result = sscanf(line, "%u-%u-%u,%f,%f,%[^,],%[^,],%f%c,%f%c", &year,
&month,&day, &temp, &uncertainty, city, country, &latitude, &lat, &longitude, &lon);
printf("%u-%u-%u,%f,%f,%s,%s,%f%c,%f%c\n", year, month, day, temp, uncertainty,
city, country, latitude, lat, longitude, lon);
printf("sscanf read %i variables\n", result);
}
int main() {
char line[] = "2013-08-01,19.005,3.621,Addis Abeba,Ethiopia,8.84N,38.11E";
char line2[] = "1816-03-01,27.426,1.793,Bangkok,Thailand,13.66N,99.91E";
char line3[] = "1743-11-01,3.264,1.665,New York,United States,40.99N,74.56W";
printLine(line);
printLine(line2);
printLine(line3);
}
它读取的某些行正确,而某些行则不读取最后一个字符。我不确定导致这个bug的原因,我可能会调用某种未定义的行为,但我不确定它是什么。
答案 0 :(得分:2)
如评论中所述,E
正在被视为浮动的一部分。您可以使用此代码将float读取为字符串,然后将其转换为float:
void printLine(char* line) {
char lat, lon;
unsigned int year, month, day;
float temp, uncertainty;
char latitude[100], longitude[100];
float latFloat, longFloat;
char country[100], city[100];
char blah[100];
int result;
result = sscanf(line, "%u-%u-%u,%f,%f,%[^,],%[^,],%[0-9.]%c,%[0-9.]%c", &year,
&month, &day, &temp, &uncertainty, city, country, latitude, &lat, longitude, &lon);
latFloat = atof(latitude);
longFloat = atof(longitude);
printf("%u-%u-%u,%f,%f,%s,%s,%f%c,%f%c\n", year, month, day, temp, uncertainty,
city, country, latFloat, lat, longFloat, lon);
printf("sscanf read %i variables\n", result);
}