我需要一个fscanf参数的解释
您好,我需要更好地解释fscanf参数。 我有以下文本文件我需要一个fscanf参数的解释,c,scanf,C,Scanf,您好,我需要更好地解释fscanf参数。 我有以下文本文件 this is line 1 this is line 2 this is line 3 ... 读出我喜欢的内容 for(int i=0;i<2;++i){ test[255]; fscanf(fp,"%[\n]",test); printf("%s\n",test); } now I get: this is line 1 this is line 1 with "%[^\n]\n" I get this
this is line 1
this is line 2
this is line 3
...
读出我喜欢的内容
for(int i=0;i<2;++i){
test[255];
fscanf(fp,"%[\n]",test);
printf("%s\n",test);
}
now I get:
this is line 1
this is line 1
with "%[^\n]\n"
I get
this is line 1
this is line 2
一直读到换行符,并跳过下一个字符,即换行符。
遵循此逻辑%[^\n]将是除换行符以外的所有字符。我会写
for(int i=0;i<2;++i){
test[255];
fscanf(fp,"%[a-z]",test);
printf("%s\n",test);
}
但我明白了
ٷ�
ٷ�
分机3
这个问题不可重复
正如我想阅读完整的一行一样,使用
scanf
函数族是一个解释输入流中剩余内容的练习。格式说明符%[^\n]
使用字符类(而不是'\n'
)进行读取,直到换行符出现为止--允许使用空格进行字符串输入。字符类(例如,[…]
)匹配括号内的内容,而'^'
作为字符类中的第一个字符会反转匹配。转换完成后,'\n'
行的结尾留在输入缓冲区中
由于字符串转换在遇到换行符时结束,而不删除保留在输入缓冲区中的'\n'
,因此下次读取尝试在不读取任何字符的情况下终止(输入失败),因此test
的值保持不变(保留第一行的值),因此再次打印时,你会得到同样的结果
从man 3 scanf
s Matches a sequence of non-white-space characters; ... The input string stops
at white space or at the maximum field width, whichever occurs first.
[ Matches a nonempty sequence of characters from the specified set of accepted
characters; ... The usual skip of leading white space is suppressed.
当您更改格式字符串以包含换行符(“%[^\n]\n”
)时,只需删除保留的换行符即可。因此,下一次尝试读取时会看到第二行的第一个字符,并且读取正确。您还可以使用(“%[^\n]%*c”
)使用赋值抑制运算符“*”
,读取并丢弃字符类后面的下一个字符
这种缺陷(未能考虑输入缓冲区中保留的字符)是鼓励新的C程序员使用
fgets
(或POSIXgetline
)进行面向行的输入的主要原因之一,因为这两个函数都读取到(并包括)它们填充的缓冲区中的换行符--消除了未读的可能性--只是等待在下次阅读时出现问题。谢谢您的解释。但有一件事我不明白,当我做“%[a-z]”时,我会得到垃圾。但是%[^\n]有什么区别呢。当然,后者接受除newline之外的所有内容。但它不应该是“这是第一行”中的“这”吗。因为a-z中的每个字符都是空的。它将[a-z]
只匹配小写字符。没有空间等。。它也不会读取尾随的换行符。您可以使用%254[a-z]“
将输入正确限制为254
字符,以避免填充超出数组边界。您不应该得到垃圾,但除非您考虑任何非小写字符和'\n'
,否则您将遇到问题。建议fgets(测试、大小测试、fp)代码>而不是fscanf
。然后你需要做的就是size\u t len=strlen(测试);如果(len&&test[len-1]='\n')test[--len]=0
从测试
中删除尾随换行符。如果您想编辑您的问题并在当前问题的末尾添加您遇到问题的代码,我很乐意提供帮助。我很难对我不得不猜测的代码进行故障排除:
)(只需删除另一条注释,让我知道您添加了代码,我来看看)添加了另一条注释
ٷ�
ٷ�
s Matches a sequence of non-white-space characters; ... The input string stops
at white space or at the maximum field width, whichever occurs first.
[ Matches a nonempty sequence of characters from the specified set of accepted
characters; ... The usual skip of leading white space is suppressed.