简体   繁体   English

fscanf和换行符

[英]fscanf and newline character

I have fscanf to read lines of setting from a configuration file. 我有fscanf从配置文件中读取设置行。 Those settings have strictly predefined format which looks like 这些设置具有严格预定义的格式,看起来像

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 BTW:通过写这个来吞掉换行符

"%[^=]=%[^;];\n"

is not elegent I think for that the newline character could repeat more than once anywhere. 我认为,换行符可能会在任何地方重复不止一次。

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). 空白字符:该函数将读取并忽略在下一个非空白字符之前遇到的任何空白字符(空白字符包括空格,换行符和制表符 - 请参阅isspace)。 A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none). 格式字符串中的单个空格验证从流中提取的任何数量的空白字符(包括无)。

An alternative is to use fgets() to read the entire line into a string, then use sscanf() . 另一种方法是使用fgets()将整行读入字符串,然后使用sscanf() This has an advantage in debugging in that you can see exactly what data the function is working on. 这在调试方面具有优势,因为您可以准确地看到该函数正在处理哪些数据。

This will work: 这将有效:

fscanf(configuration,"%[^=]=%[^;];%[^\\n]",name,option,dummy);

You will have to consume the new line character.Otherwise,the newline is left in the input stream. 您将不得不使用换行符。否则,换行符将保留在输入流中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM