gpt4 book ai didi

c - Sscanf 没有以相同的方式读取相同的行

转载 作者:行者123 更新时间:2023-12-02 01:01:12 26 4
gpt4 key购买 nike

#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);
}

有些行它可以正确读取,有些行它没有读取最后一个字符。我不确定是什么导致了这个错误,我可能正在调用某种未定义的行为,但我不确定它是什么。

最佳答案

如评论中所述,E 被作为 float 的一部分读取。您可以使用此代码将 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);
}

关于c - Sscanf 没有以相同的方式读取相同的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50477114/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com