【问题标题】:Width as a variable when using fscanf [duplicate]使用 fscanf 时将宽度作为变量 [重复]
【发布时间】:2011-03-19 19:17:13
【问题描述】:

我正在尝试读取文件的某个部分,并且每行的数据量不同,但我知道我想要多少字节的信息。像这样:

5bytes.byte1byte2byte3byte4byte5CKSum //where # of bytes varies for each line (and there is no period only there for readability)  

实际数据:

05AABBCCDDEE11
03AABBCC22
04AABBCCDD33

所以我想让我的宽度是这样的变量:

fscanf_s(in_file,"%variableX", &iData);  

这可能吗,因为现在我想我必须创建一个案例陈述?

【问题讨论】:

  • 你需要澄清你在问什么。
  • 基本上我只是希望能够使用一个变量来设置宽度,我可以根据我阅读的每一行而不是“%5X”来更改该变量 - 这里我的宽度限制为 5,我只是想把我自己的变量放在那里,所以我的宽度可以是动态的。

标签: c++ c width scanf


【解决方案1】:

带有 %X 的 fscanf 会自动在换行处停止,对吗?如果这些字段确实是换行符终止的(如您的示例中所示),那么您不能直接调用

fscanf(in_file, "%X", &iData);

并让 fscanf 找出终点在哪里?

【讨论】:

  • 是的,没错,我实际上犯了一个错误,最后有一个我不想要的校验和。所以这对我不起作用。
【解决方案2】:

不幸的是,不,没有像'*'这样的修饰符用于 printf 导致 scanf 从变量中获取其字段宽度或精度。最接近的方法是动态创建格式字符串:

char format[8];
sprintf(format, "%%%dX", width);
fscanf(in_file, format, &iData);

【讨论】:

  • 你有in+file,应该是in_file。
【解决方案3】:

您也可以考虑使用 C++ 流。

#include <ifstream>
#include <iostream>

// open the file and create a file input stream
ifstream file("test.txt" , ios::in | ios::binary);

// loop through the whole file
while (ifs.good())
{
    // extract one byte as the field width
    unsigned char width;
    file.read(&width, 1);

    // extract width number of unformatted bytes
    char * bytes = new char[width];
    file.read(bytes, width);

    // process the bytes
    ...
    delete [] bytes;

    // skip EOL characters if needed
    // file.seekg(1, ios_base::cur)
}

file.close();

如果按照您的指示包含换行符,则更简单的方法是使用 getLine()。查看http://www.cplusplus.com/reference/iostream/ifstream/ 了解更多使用 read()、get()、getLine() 和许多其他出色的流函数的方法。

【讨论】:

    【解决方案4】:

    我认为最简单的方法是像这样使用 fread()

    fread(buffer, nbytes, sizeof(char), in_file);
    

    【讨论】:

      【解决方案5】:

      如果您真的希望能够以编程方式调整 fscanf 格式,您可以尝试堆栈分配具有足够空间的字符串,然后生成如下格式: 例如

      char formatString[100];
      
      // writes "%max_size[0-9]", substituting max_size with the proper digits
      sprintf(formatString, "%%%d[0-9]", MAX_SIZE); 
      
      fscanf(fp, formatString, buffer); // etc...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-20
        • 1970-01-01
        • 2019-12-23
        • 2013-06-30
        • 2015-10-15
        • 1970-01-01
        • 2021-10-14
        相关资源
        最近更新 更多