【问题标题】:fscanf not reading/recognizing float numbers?fscanf 不读取/识别浮点数?
【发布时间】:2019-10-24 21:06:05
【问题描述】:

我正在尝试从具有以下格式的文件中读取:

 ID: x y z ...... other crap 

第一行如下所示:

 0: 0.82 1.4133 1.89 0.255 0.1563 armTexture.jpg 0.340 0.241 0.01389

我只需要 x y z 浮点数,该行的其余部分是垃圾。 我的代码目前如下所示:

int i;
char buffer[2];
float x, y, z;

FILE* vertFile = fopen(fileName, "r");      //open file
fscanf(vertFile, "%i", &i);                 //skips the ID number
fscanf(vertFile, "%[^f]", buffer);      //skip anything that is not a float (skips the : and white space before xyz)

//get vert data
vert vertice = { 0, 0, 0 };
fscanf(vertFile, "%f", &x);
fscanf(vertFile, "%f", &y);
fscanf(vertFile, "%f", &z);

fclose(vertFile);

为了调试做了一点改动(最初前两个 scanfs 使用 * 来忽略输入)。

当我运行它时,x、y、z 不会改变。如果我成功了

int result = fscanf(vertFile, "%f", &x);

结果是 0,我相信这告诉我它根本没有将数字识别为浮点数?我尝试将 xyz 切换为双精度并使用 %lf,但这也不起作用。

我做错了什么?

【问题讨论】:

  • 您从哪里得知%[^f] 跳过了非浮点数?
  • Welp,我有点用这个:stackoverflow.com/questions/2799612/…
  • 但我才意识到我是个白痴,因为他用它来跳过任何不是换行符的东西。我不确定为什么我的大脑认为它适用于 %f lmao。
  • 您应该使用fgets 阅读整行,然后使用sscanf 提取三个数字。

标签: c scanf


【解决方案1】:

%[^f] 不会跳过非浮点数,它会跳过不是字母 'f' 的任何内容。

改用%*d:。 * 丢弃读取的数字,而文字 : 告诉它跳过冒号。您还可以组合所有这些单独的读取。

fscanf(vertFile, "%*d: %f %f %f", &x, &y, &z);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-17
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多