【问题标题】:reading CSV with scanf and scanset with multiple decimals [duplicate]使用 scanf 和 scanset 读取多位小数的 CSV [重复]
【发布时间】:2018-04-14 21:48:10
【问题描述】:

按照this question 中的扫描集格式,我尝试了一种稍微不同的格式来读取多个数字而不是一个数字。这是我的数据:

722280,"BIRMINGHAM MUNICIPAL AP",AL,-6.0,33.567,-86.750,189

这是我的代码:

char buf[400];
char station[11], city[101], state[11];
int tz, lat, lon, alt;
fgets(buf, sizeof buf, file) // yes, I test this 
sscanf( buf, "%10[^,],%100[^,],%10[^,],%d,%d,%d,%d", station, city, state, &tz, &lat, &lon, &alt);

当我运行它时,车站、城市、州和 tz 都已正确设置。但是,lat、lon 和 alt 不是 - 例如 lat 是 1,lon 是 0。

我在字符串上尝试了多种变体,包括 %d 后的 [^,] 和删除逗号,但都没有运气。

是的,我知道我可以使用 strtok 或众多变体中的一个来做到这一点,但我想尝试 sscanf,因为它匹配一组类似的代码,我想让它们保持相似,如果可能。

我怀疑这是可能的,我正在考虑格式?

【问题讨论】:

  • 它们是浮点数,而不是int。您在sscanf 中使用%d 格式。
  • 天啊。这就是 C&P 所得到的。
  • 总是检查scanffamily的返回值:成功转换的项目数。
  • 我用真实的代码做测试,这是我的sim。嗯,所以我这样做了: "%10[^,],%100[^,],%10[^,],%d,%f,%f,%d" 我得到了相同的行为。跨度>
  • 您在文本输入示例中有 3 个浮点值,但在注释的“真实代码”中只有 2 个 %f。他们是int 还是float 还是double?变量都是int

标签: c scanf


【解决方案1】:

按照建议使用正确的格式以及正确的数据类型。这应该有效:

int main(void)
{
    FILE *file = fopen("test.txt", "r");

    char buf[400];
    char station[11], city[101], state[11];
    float tz, lat, lon;
    int alt;

    while(fgets(buf, sizeof(buf), file))
    {
        sscanf(buf, "%10[^,],%100[^,],%10[^,],%f,%f,%f,%d", 
            station, city, state, &tz, &lat, &lon, &alt);

        printf("%s\n%s\n%s\n%f\n%f\n%f\n%d\n\n", station, city, state, tz, lat, lon, alt);
    }

    return 0;
}

【讨论】:

  • 您需要对city 进行进一步处理以删除引号。将城市读入tmp 变量,然后使用strncpy (city, tmp +1, strlen (tmp) - 2) 或类似的东西就可以了。 (除非你想在字符串的每一端挂上无用的双引号)
  • 关于:FILE *file = fopen("test.txt", "r"); Always check (!=NULL) the returned value to assure the operation was successful. If not successful, call perror("fopen test.txt for read failed");`这将输出封闭的文本和系统认为函数失败的文本原因stderr。使用exit( EXIT_FAILURE ); 关注该电话
猜你喜欢
  • 1970-01-01
  • 2018-01-10
  • 2012-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多