fscanf and newline character

匿名 (未验证) 提交于 2019-12-03 01:00:01

问题:

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.

回答1:

Just add space at the end of the format string:

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

This will eat all whitespace characters, including new-lines.

Quotation from 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).



回答2:

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.



回答3:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!