[英]What's differernce betwen scanf(“%s”), scanf(“ %s”) and scanf(“%s ”)?
I am confused with this syntax. 我对此语法感到困惑。 At first, I thought it was a printing error in the book.
起初,我认为这是书中的印刷错误。 But, while programming for quite a long time I came to know that they have different meaning.
但是,在编程很长一段时间后,我才知道它们具有不同的含义。 Still, I'm not able to get clear vision about that syntax.
尽管如此,我仍无法对该语法有清晰的了解。
Likewise, what's difference between: 同样,两者之间有什么区别?
gets( str);
and gets(str);
并
gets(str);
Does whitespace matter? 空格重要吗? If yes, then how?
如果是,那怎么办?
When adding a space in the scanf
format string, you tell scanf
to read and skip whitespace. 在
scanf
格式字符串中添加空格时,您告诉scanf
读取和跳过空格。 It can be usefull to skip newlines in the input for example. 例如,跳过输入中的换行符可能很有用。 Also note that some formats automatically skip whitespace anyway.
还要注意,某些格式仍然会自动跳过空格。
See eg here for a good reference of the scanf
family of functions. 请参见此处,以获得
scanf
系列功能的良好参考 。
The difference between 和...之间的不同
gets(str);
and 和
gets( str );
is none at all. 一点都不。 Actual code outside of string literals can be formatted with any amount of whitespace.
字符串文字之外的实际代码可以使用任意数量的空格格式化。 You could even write the above call as
您甚至可以将上述通话写为
gets
(
str
)
;
It would still be the same. 还是一样。
Oh, and the gets
function is deprecated since long ago, and even removed from the latest C standard. 哦,很久以前不赞成使用
gets
函数,甚至从最新的C标准中删除了它。 You should use fgets
instead. 您应该改用
fgets
。
White space (such as blanks, tabs, or newlines) in the format string match any amount of white space, including none , in the input.
格式字符串中的空格(例如空格,制表符或换行符)与输入中的任何空格数量都匹配,包括none 。
http://www.manpagez.com/man/3/scanf/ http://www.manpagez.com/man/3/scanf/
In gets
the space does not mean anything. 在
gets
空间并不意味着任何东西。 Its ignored on compile time. 它在编译时被忽略了。
编译器具有多个阶段,并且在第一阶段词法分析中,所有不必要的空格都将被删除,这也是当时将要删除的不必要的空间,因此, gets(a) and gets( a)
之间没有区别。
There are two important things to learn about scanf here: 关于scanf,有两个重要的知识要学习:
You can explicitly invoke this behavior of ignoring all whitespace as follows: 您可以显式调用忽略所有空格的行为,如下所示:
scanf(" %c", &mychar)
scanf("\\n%c", &mychar)
scanf("\\t%c", &mychar)
That is, any whitespace character (including spaces) in your conversion string instructs scanf to ignore any and all whitespace up until the scanned item. 也就是说,转换字符串中的任何空格字符(包括空格)都会指示scanf忽略所有空格直到被扫描的项目为止。
Since all conversion modifiers except %c and %[ do this automatically, the answer to your original question about scanf("%s")
versus scanf(" %s")
is that there is no difference. 由于除%c和%[外的所有转换修饰符都是自动执行的,因此您对
scanf("%s")
和scanf(" %s")
的原始问题的答案是没有区别。
I would recommend reading all the scanf questions at the C FAQ and writing some test programs to get a better grasp of it all: 我建议阅读C FAQ上的所有scanf问题,并编写一些测试程序以更好地掌握所有内容:
http://c-faq.com/stdio/scanfprobs.html http://c-faq.com/stdio/scanfprobs.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.