我正在尝试从具有以下格式的文件中读取:
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 切换为 double 并使用 %lf ,但这也不起作用。
我可能做错了什么?
最佳答案
%[^f]
不跳过非浮点数,它跳过任何不是字母 'f'
的内容.
试试 %*d:
反而。 *
丢弃读取的数字和文字 :
告诉它跳过冒号。您还可以组合所有这些单独的读取。
fscanf(vertFile, "%*d: %f %f %f", &x, &y, &z);
关于c - fscanf 不读取/识别 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58549126/