本文介绍了fscanf和换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有fscanf从配置文件中读取设置的行。这些设置具有严格的预定义格式,如

  name1 = option1; 
name2 = option2;
...

所以基本上我做了

  fscanf(configuration,%[^ =] =%[^;];,name,option); 

其中配置是文件流,名称和选项是编程缓冲区。 b

问题是名称缓冲区包含我不想要的换行符。有没有格式说明符我已经错过了[^ ...]设置为跳过换行符?无论如何,它可以通过格式说明符来解决吗?

顺便说一句:通过写这个字符来吞并换行符

 %[^ =] =%[^;]; \\\

是不是elegent我认为换行符可以重复不止一次。

格式字符串的结尾:

 %[^ =] =%[^;];


这将会包含所有空格字符,包括换行符。



来自的报价:


空格字符:函数将读取并忽略在下一个非空白字符(空格字符包括空格,换行符和制表符 - 见isspace)之前遇到的任何空格字符。格式字符串中的单个空格验证从流中提取的任何数量的空白字符(包括none)。


I have fscanf to read lines of setting from a configuration file. 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

"%[^=]=%[^;];\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:

这篇关于fscanf和换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 19:41