I am reading a string from stdin
using the scanf
function.
char inputWord[100];
scanf("%99[^\n]", inputWord);
This works fine except the case when the first character in the input sequence is a newline (entered by pressing the enter key
). When I print the length of inputWord using strlen
, it prints 6 (always) and when I print the inputWord
string itself, it prints some garbage. man
page of scanf
states that a terminating null byte is added after the first match of a character in the input sequence with the set of excluded characters which here is [^\\n]
. Why is it not adding a null byte in this case? Is it because scanf
cannot match any character in this case (return value is zero)?
I know I should be using fgets
but I am just curious to know the behaviour of scanf
in this case. Seems like scanf
is one beast of a function.
在这种情况下, scanf()
的返回码将为0,因为它与转换规范的任何内容都不匹配(因为转换规范没有匹配,nothign会写入相应的变量)。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.