在C中阅读标签

时间:2014-07-17 10:27:35

标签: c scanf

我正在尝试从文件中删除sscanf。我想要匹配的模式如下 “%S \吨%S \吨%S \吨%F”

因为输入如下,我感到很惊讶: 你好Hola Hallo 5.344434

它正在正确读取所有数据......

你知道为什么吗?

我期待它找到像| --- | --- | --- | --- |这样的标签并非只有一个空间匹配。

由于

4 个答案:

答案 0 :(得分:3)

standard读取:

  

由空白字符组成的指令由执行   读取输入到第一个非白色空间字符(仍然存在   未读),或直到不再能读取任何字符。

换句话说,格式字符串中的一系列空白字符(空格,制表符,换行符等;由isspace()定义)与输入中的任意数量的空格<匹配< /强>

答案 1 :(得分:2)

如果您查看scanf的{​​{3}}:

C string that contains a sequence of characters that control how characters extracted from the stream are treated:
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).
Non-whitespace character, except format specifier (%): Any character that is not
either a whitespace character (blank, newline or tab) or part of a format specifier
(which begin with a % character) causes the function to read the next character 
from the stream, compare it to this non-whitespace character and if it matches,
it is discarded and the function continues with the next character of format. If the
character does not match, the function fails, returning and leaving subsequent 
characters of the stream unread.
Format specifiers: A sequence formed by an initial percentage sign (%) indicates a
format specifier, which is used to specify the type and format of the data to be
retrieved from the stream and stored into the locations pointed by the additional
arguments.

您会注意到空格字符会被忽略。

答案 2 :(得分:2)

没办法 - scanf同等地处理所有空白 - 它们被用作分隔符,只是被忽略了。所以,如果你真的想用标签空间做一些事情,你应该自己解析它。

要解析,您需要在不进行任何解析的情况下读取整行,与 scanf 不同。因此,您需要使用fgets

FILE *fp = /* init.. */;
char buf[1024];
fgets(buf, 1024, fp);
// parse yourself!

答案 3 :(得分:0)

您是否仔细阅读scanf(3)文档?您需要使用getline(3)读取整行,然后解析该行&#34;手动&#34;!