【问题标题】:fscanf not placing values in variablesfscanf 没有将值放入变量中
【发布时间】:2014-09-20 23:44:19
【问题描述】:

我在使用 fscanf 读取 3 个变量的文件中有 3 个值(由空格分隔)。出于某种原因,这些值没有改变。当我打印这些值时,它会打印内存垃圾/我将它们的初始值设置为什么。我也尝试过将 fgets 与 sscanf 一起使用,但没有骰子。

代码:

int numPresale; // The number of presale tickets sold
double costPresale; // The cost of presale tickets
double costDoor;    // The cost of tickets sold at the door

// Opens the file. Exits program if it can't
if((inFile = fopen(fileName, "r")) == NULL) {
    printf("Unable to open the input file '%s'\n", fileName);
    exit(EXIT_FAILURE);
}

// Parse for information
fscanf(inFile, "%.2f %.2f %d", &costPresale, &costDoor, &numPresale);

printf("%.2f %.2f %d", costPresale, costDoor, numPresale);

fclose(inFile);

我确定我犯了一些经典的菜鸟错误,但我在网上找不到任何答案。提前感谢您的帮助!

【问题讨论】:

  • 另外,请始终检查返回值。并使用完整的警告:-Wall -Wextra -pedantic.

标签: c fgets scanf


【解决方案1】:

值不变的原因是fscanf 找不到与您指定的格式匹配的值。此外,不需要空格。最后,由于您将数据读入double,而不是float,因此您应该使用%lf 作为格式说明符。

您可以通过检查fscanf的返回值来检查是否收到了正确数量的项目。

这应该可以解决这个问题:

if (fscanf(inFile, "%lf%lf%d", &costPresale, &costDoor, &numPresale) == 3) {
    printf("%.2f %.2f %d", costPresale, costDoor, numPresale);
}

Demo.

【讨论】:

  • .2f 不需要两个位置。对于scanf,它只是一个无效的格式字符串。 . 字符不用于scanf 格式。
猜你喜欢
  • 2019-12-23
  • 1970-01-01
  • 1970-01-01
  • 2014-05-18
  • 1970-01-01
  • 2017-02-04
  • 2021-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多