我有一个包含以下内容的文本文件:
"abc","def","ghi"
以下工作可以正确读取文件内容:
int main()
{
char name[1024] = {0};
FILE *file = fopen("file.txt", "r");
while(1)
{
if (fscanf(file, " %[\",]s ", name) == EOF)
break;
if (fscanf(file, " %[a-zA-Z]s ", name) == EOF)
break;
printf("%s\n", name);
}
return 0;
}
但是,以下操作失败了:
int main()
{
char name[1024] = {0}, garbage[5];
FILE *file = fopen("file.txt", "r");
while(1)
{
if (fscanf(file, " %[\",]s%[a-zA-Z]s ", garbage, name) == EOF)
break;
printf("%s\n", name);
}
return 0;
}
我正在使用 MSVC++ 08。我缺少什么?我正在寻找在 while
循环中使用单个 fscanf()
的解决方案。
最佳答案
有用吗???纯粹的倒霉:-)
您的转换规范意味着
" %[\",]s "
^= optionally skip whitespace
^== read a literal 's'
^^^^^^=== read an unlimited string of quotes and commas
^========= optionally skip whitespace
和
" %[a-zA-Z]s "
^= optionally skip whitespace
^== read a literal 's'
^^^^^^^^^=== read an unlimited string of letters
^============ optionally skip whitespace
和
" %[\",]s%[a-zA-Z]s "
^= optionally skip whitespace
^== read a literal 's'
^^^^^^^^^=== read an unlimited string of letters
^============ read a literal 's'
^^^^^^============= read an unlimited string of quotes and commas
^=================== optionally skip whitespace
我觉得你想要
" %4[\",]%1023[a-zA-Z] "
^= optionally skip whitespace
^^^^^^^^^^^^^== read a string of at most 1023 letters
^^^^^^^=============== read a string of at most 4 quotes and commas
^====================== optionally skip whitespace
除此之外,scanf
返回成功转换的次数或出错时返回 EOF。当您应该与 1(或 2,或其他)进行比较时,您正在将结果值与 EOF 进行比较:与您期望的转化次数进行比较。
if (scanf() == 3) /* expected 3 conversions */
{ /* ok */ }
else { /* oops, something went wrong */ }
关于c - 在 fscanf() 中使用 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3981958/