所以我的输入文件看起来像...
(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;
}
- 将变量的地址而不是变量本身传递给
fscanf()
。 category
和detail
应该是 char 数组,因为它们应该包含字符串。- 在格式字符串中添加一个前导空格以丢弃 Enter 留下的
'\n'
。 - 使用
%80[^%]%*[^%]
避免缓冲区溢出。
但是,如您所见,这段代码的可读性极差。最好使用fgets()
,然后使用其他函数获取所需的信息。
关于C编程,如何在多个字段类型中使用定界符%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36852892/