2014-07-17 76 views
-2

我想从文件中sscanf。我想匹配的模式为以下 “%S \ t%S \ t%S \ T%F”在C中读取标签

的事情是,我很惊讶,因为像下面输入: 你好HOLA喂5.344434

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

你知道为什么吗?

我一直在期待它找到像| --- | --- | --- | --- |不是只有一个空间是匹配的。

由于

回答

2

不可能 - scanf同等对待所有空格 - 它们被用作分隔符,并且被忽略。所以如果你真的想用tab空间做一些事情,你应该自己解析它。

要解析,您需要阅读整行而不进行任何解析,不像scanf。所以,你需要使用fgets

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

'getline'比'fgets'更好,因为它不会限制电流线的长度(当然除了资源枯竭,即出现内存不足的) –

+0

@BasileStarynkevitch肯定的,但它不是** **标准C> o < – ikh

3

standard读取:

的空白字符(一个或多个)构成的指令通过 读取输入执行到第一个非空白字符(这仍然是 未读),或直到没有更多的字符可以被读取。

换言之,的(如由isspace()定义空格,制表,换行,等;)空白字符在格式字符串的序列相匹配的白色空间的任何量在输入

0

您是否认真阅读scanf(3)文档?您需要使用getline(3)来读取整行,然后“手动”解析该行!

2

如果你看一看的documentationscanf

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. 

你会发现,空白字符会被忽略。