fscanf无法读取/识别浮点数?

4

我正在尝试读取一个格式为:

的文件。

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

为了调试,它稍作修改(最初的前两个scanf使用*忽略输入)。

当我运行这段代码时,x、y、z并没有改变。如果我这样做

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

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

我可能做错了什么?


3
你是从哪里得到%[^f]会跳过非浮点数的想法的? - Steve Summit
我有点在使用这个:https://dev59.com/bHE85IYBdhLWcg3wYigB - SloanTheSloth
但我突然意识到自己很蠢,因为他正在使用它来跳过任何不是换行符的内容。我不确定为什么我的大脑认为它会对%f有效哈哈。 - SloanTheSloth
2
你应该使用 fgets 读取整行,然后再用 sscanf 提取三个数字。 - user3386109
1个回答

5

%[^f]并非跳过非浮点数,而是跳过除字母'f'之外的任何内容。

尝试使用%*d:代替。*表示丢弃读取的数字,而文本:表示跳过冒号。您还可以将所有这些单独读取组合在一起。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接