C编程,如何在多个字段类型中使用定界符%

标签 c file io

所以我的输入文件看起来像...

(int)%(char)%(char)%(double)%(int)%(int)%(int)

例子是

2%restaurant%denny's%12.40%2016%4%21
3%gas%shell%15.20%2016%3%22

我试过使用这段代码(fp 是文件指针)

while(fscanf(fp, "%d%%%c%%%c%%%lf%%%d%%%d%%%d", id, category, detail, amount, year, month, day) == 7){//Some code that uses it//}

代码应该读取输入文件并为 % 之间的每个变量设置值,然后我可以以某种方式使用它。 问题是我遇到了几个错误,想知道我是否做对了。

最佳答案

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *fp = fopen("data.txt", "r");
    if(!fp)
        exit(EXIT_FAILURE);
    int count = 7;
    int id, year, month, day;
    char category[81], detail[81];
    double amount;
    while(count == 7)
    {
        count = 0;
        count += fscanf(fp, " %d%%%80[^%]", &id, category);
        fscanf(fp, "%*[^%]");
        count += fscanf(fp, "%%%80[^%]", detail);
        fscanf(fp, "%*[^%]");
        count += fscanf(fp, "%%%lf%%%d%%%d%%%d", &amount, &year, &month, &day);
        if(count == 7)
            printf("%d%%%s%%%s%%%g%%%d%%%d%%%d\n", id, category, detail, amount, year, month, day);
    }
    return EXIT_SUCCESS;
}
  1. 将变量的地址而不是变量本身传递给 fscanf()
  2. categorydetail 应该是 char 数组,因为它们应该包含字符串。
  3. 在格式字符串中添加一个前导空格以丢弃 Enter 留下的 '\n'
  4. 使用 %80[^%]%*[^%] 避免缓冲区溢出。

但是,如您所见,这段代码的可读性极差。最好使用fgets(),然后使用其他函数获取所需的信息。

关于C编程,如何在多个字段类型中使用定界符%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36852892/

相关文章:

file - 分配文件() : File access denied

c++ - 用文件内容的第一行替换文件名

c - rewind() 之后,您可以使 fprintf() 写入文件末尾吗(例如完全覆盖)

c - 类型安全与松散类型 - GO 与 C

c - 理解 C 中的指针

c++ - ofstream - 检测文件是否在打开和关闭之间被删除

python - 为什么读取一个字节比从文件中读取 2、3、4……字节慢 20 倍?

c++ - 如果输入错误则无限循环

c - 引用计数如何工作?

C 在 32 位系统上产生错误的结果