14

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

name1=option1;
name2=option2;
...

所以基本上我会

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

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

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

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

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

我认为这并不优雅,因为换行符可以在任何地方重复多次。

4

3 回答 3

15

只需在格式字符串的末尾添加空格:

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

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

于 2012-11-04T19:16:53.557 回答
8

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.

于 2012-11-04T19:28:34.523 回答
1

这将起作用:

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

您将不得不使用换行符。否则,换行符将留在输入流中。

于 2012-11-04T19:14:55.337 回答