C语言 fscanf 和换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13221844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
fscanf and newline character
提问by Yang
I have fscanf to read lines of setting from a configuration file. Those settings have strictly predefined format which looks like
我有 fscanf 从配置文件中读取设置行。这些设置具有严格的预定义格式,看起来像
name1=option1;
name2=option2;
...
so basically I do
所以基本上我做
fscanf(configuration,"%[^=]=%[^;];",name,option);
where configuration is the file stream and name and option are programming buffers.
其中配置是文件流,名称和选项是编程缓冲区。
The problem is that the name buffer contains a newline character I don't want. Is there format specifier I've missed in the "[^...]" set to skip newline character? Anyway, can it be solved through format specifier ever?
问题是名称缓冲区包含我不想要的换行符。在“[^...]”设置中是否遗漏了格式说明符以跳过换行符?无论如何,它可以通过格式说明符解决吗?
BTW: Swallowing the newline character by writting this
顺便说一句:通过写这个吞下换行符
"%[^=]=%[^;];\n"
is not elegent I think for that the newline character could repeat more than once anywhere.
不太优雅,我认为换行符可以在任何地方重复多次。
采纳答案by Evgeny Kluev
Just add space at the end of the format string:
只需在格式字符串的末尾添加空格:
"%[^=]=%[^;]; "
This will eat all whitespace characters, including new-lines.
这将吃掉所有空白字符,包括换行符。
Quotation from cplusplus.com:
来自cplusplus.com 的报价:
Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).
空白字符:该函数将读取并忽略在下一个非空白字符之前遇到的任何空白字符(空白字符包括空格、换行符和制表符——请参阅 isspace)。格式字符串中的单个空格验证从流中提取的任意数量的空格字符(包括无)。
回答by Clifford
An alternative is to use fgets()to read the entire line into a string, then use sscanf(). This has an advantage in debugging in that you can see exactly what data the function is working on.
另一种方法是使用fgets()将整行读入一个字符串,然后使用sscanf(). 这在调试中具有优势,因为您可以准确查看函数正在处理的数据。
回答by askmish
This will work:
这将起作用:
fscanf(configuration,"%[^=]=%[^;];%[^\n]",name,option,dummy);
fscanf(configuration,"%[^=]=%[^;];%[^\n]",name,option,dummy);
You will have to consume the new line character.Otherwise,the newline is left in the input stream.
您将不得不使用换行符。否则,换行符会留在输入流中。

