c - 从文件中读取带空格的固定大小寄存器

标签 c file scanf

我试图从 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/

相关文章:

c - OpenSSL rsa 例程 :RSA_padding_check_PKCS1_type_2:pkcs decoding error

javascript - 当多个文件被删除时,FileReader 只读取一个文件

c - IFileOperation::DeleteItem 在系统目录 .Local 中不起作用

c - scanf 之后 fgets 不起作用

c - scanf 的返回值和输入验证

c++ - (隐藏?)影响 C/C++ 编译的 MS Visual Studio 设置

使用 strdup 从字符串转换的 c++ char* 不等于原始原始字符串

c - 用用户输入填充 *char[]

c - 通过前缀在树中查找单词

在 URL 文件扩展名中使用 CAPS 时,Php 文件在 Palapa 网络服务器(Lighttpd 服务器)中公开