我有一个包含以下内容的文本文件:
"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",]s%[a-zA-Z]s ",garbage,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 */ }