我想從文件中sscanf。我想匹配的模式爲以下 「%S \ t%S \ t%S \ T%F」在C中讀取標籤
的事情是,我很驚訝,因爲像下面輸入: 你好HOLA喂5.344434
它正在讀取所有數據...
你知道爲什麼嗎?
我一直在期待它找到像| --- | --- | --- | --- |不是隻有一個空間是匹配的。
由於
我想從文件中sscanf。我想匹配的模式爲以下 「%S \ t%S \ t%S \ T%F」在C中讀取標籤
的事情是,我很驚訝,因爲像下面輸入: 你好HOLA喂5.344434
它正在讀取所有數據...
你知道爲什麼嗎?
我一直在期待它找到像| --- | --- | --- | --- |不是隻有一個空間是匹配的。
由於
不可能 - scanf
同等對待所有空格 - 它們被用作分隔符,並且被忽略。所以如果你真的想用tab空間做一些事情,你應該自己解析它。
要解析,您需要閱讀整行而不進行任何解析,不像scanf。所以,你需要使用fgets
。
FILE *fp = /* init.. */;
char buf[1024];
fgets(buf, 1024, fp);
// parse yourself!
的standard讀取:
的空白字符(一個或多個)構成的指令通過 讀取輸入執行到第一個非空白字符(這仍然是 未讀),或直到沒有更多的字符可以被讀取。
換言之,的(如由isspace()
定義空格,製表,換行,等;)空白字符在格式字符串的序列相匹配的白色空間的任何量在輸入。
您是否認真閱讀scanf(3)文檔?您需要使用getline(3)來讀取整行,然後「手動」解析該行!
如果你看一看的documentation爲scanf
:
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.
你會發現,空白字符會被忽略。
'getline'比'fgets'更好,因爲它不會限制電流線的長度(當然除了資源枯竭,即出現內存不足的) –
@BasileStarynkevitch肯定的,但它不是** **標準C> o < – ikh