简体   繁体   English

scanf不会放置终止空字节

[英]scanf doesn't put a terminating null byte

I am reading a string from stdin using the scanf function. 我正在使用scanf函数从stdin读取一个字符串。

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 ). 除了输入序列中的第一个字符是换行符(通过按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. 当我使用strlen打印inputWord的长度时,它打印6(总是),当我打印inputWord字符串本身时,它会打印一些垃圾。 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] . scanf man页指出在输入序列中的字符与排除字符集合的第一次匹配之后添加终止空字节,这里是[^\\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)? 是因为在这种情况下scanf无法匹配任何字符(返回值为零)?

I know I should be using fgets but I am just curious to know the behaviour of scanf in this case. 我知道我应该使用fgets但我很想知道在这种情况下scanf的行为。 Seems like scanf is one beast of a function. 似乎scanf是一个函数的野兽。

在这种情况下, scanf()的返回码将为0,因为它与转换规范的任何内容都不匹配(因为转换规范没有匹配,nothign会写入相应的变量)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM