我试图从 c 中的文本文件中读取固定大小的寄存器。
寄存器的结构如下:
00030REGIST X1Y005.0
- 5 个字符的整数
- 10个字符的字符串(带空格)
- 5 个字符的 float
当我尝试读取寄存器时,我得到以下结果:
00030REGIST X1Y005.00.00000
我在字符串末尾得到一个 0.00000
#include <stdio.h>
#include <stdlib.h>
int main () {
int id;
float price;
char desc[11];
FILE * data_file;
//Reading from file
if(!(data_file = fopen("./products.txt","r"))){
printf("\nError reading file\n");
exit(2);
}
// The value of the register is 00030REGIST X1Y005.0
// But i get 00030REGIST X1Y005.00.00000
while (fscanf(data_file,"%05d %[^\n]10s %05f", &id, desc, &price) != EOF) {
printf("%05d%s%05f\n",id , desc, price);
}
fclose(data_file);
return(0);
}
最佳答案
编辑:我将程序更改为读取 10 个可以包含数字的字符串字符。
格式说明符 %[^\n]10s
是 %s
和 %[]
的奇怪混合体。我建议如下,这里只是为了示例而使用单个字符串,为了清晰起见,在输出中添加了换行符。
#include <stdio.h>
int main(void)
{
int id;
float price;
char desc[11];
char input[] = "00030REGIST X1Y005.0";
int res = sscanf(input, "%d%10[^\n]%f", &id, desc, &price);
if(res == 3) {
printf("%05d\n%s\n%05f\n",id , desc, price);
}
}
程序输出:
00030 REGIST X1Y 5.000000
关于c - 从文件中读取带空格的固定大小寄存器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56847995/