scanf()的行为感到好奇! [英] scanf() curious behaviour!

查看:125
本文介绍了scanf()的行为感到好奇!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在一个奇怪的情况下,迷迷糊糊(ATLEAST对我来说,因为我以前从来没有遇到过这样)..考虑下面的简单code: -

I recently stumbled upon a curious case(atleast for me, since I hadn't encountered this before)..Consider the simple code below:-

int x;
scanf("%d",&x);
printf("%d",x);

以上code需要一个正常的整数输入并显示预期的结果。

The above code takes a normal integer input and displays the result as expected..

现在,如果我修改上面的code以下: -

Now, if I modify the above code to the following:-

int x;
scanf("%d ",&x);//notice the extra space after %d
printf("%d",x);

这发生在另一额外的输入它给人的printf语句的结果之前。我不明白为什么在scanf函数的行为变化的空间效果()..任何人都可以给我讲解一下....

This takes in another additional input before it gives the result of the printf statement.. I don't understand why a space results in change of behaviour of the scanf().. Can anyone explain this to me....

推荐答案

从<一个href=\"http://beej.us/guide/bgc/output/html/multipage/scanf.html\">http://beej.us/guide/bgc/output/html/multipage/scanf.html:

在scanf()系列的功能从控制台或从文件流中读取数据,分析它,并在你的参数列表提供了变量的结果存储了。

The scanf() family of functions reads data from the console or from a FILE stream, parses it, and stores the results away in variables you provide in the argument list.

格式字符串非常相似,在printf()函数在你可以告诉它读取%D,例如为一个int。 但是,它也有额外的功能,最主要的是,它可以吃掉输入您在格式字符串指定其它字符

The format string is very similar to that in printf() in that you can tell it to read a "%d", for instance for an int. But it also has additional capabilities, most notably that it can eat up other characters in the input that you specify in the format string.

这是怎么回事是scanf函数是模式匹配格式字符串(有点像一个普通的前pression)。 scanf的不断消耗从标准输入(例如控制台)的文本,直到整个模式匹配。

What's happening is scanf is pattern matching the format string (kind of like a regular expression). scanf keeps consumes text from standard input (e.g. the console) until the entire pattern is matched.

在第二个例子中,scanf函数在若干,并将其存储以x读取。但是,还没有达到格式字符串的结尾 - 那里仍留有一个空格字符。因此scanf函数从标准输入读取附加的空白字符(S)以(试图)相匹配。

In your second example, scanf reads in a number and stores it in x. But it has not yet reached the end of the format string -- there is still a space character left. So scanf reads additional whitespace character(s) from standard input in order to (try to) match it.

这篇关于scanf()的行为感到好奇!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆