c 中的 scanf 和换行符 [英] scanf and newlines in c

查看:80
本文介绍了c 中的 scanf 和换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天刚刚在我的 C 课上做了一个测试,我有理由相信答案可能是不正确的.

I just had a test in my C class today and I have reason to believe that answer might be incorrect.

scanf("%d\n", &x); // Evaluate the expression for the string "54321\n"

这个想法很简单.找一个整数,把扫描到的数字放在整数变量x对应的内存位置.但是,我认为对 scanf 的调用永远不会终止.

The idea is pretty simplistic. Find an integer and place the scanned number at the memory location corresponding with integer variable x. However, I don't believe that this call to scanf would ever terminate.

就我而言,对标准 I/O 的所有对 scanf 的调用都会在按下 Enter 键时终止,因此无需在说明符字符串中包含换行符.事实上,这种冗余只会导致程序在搜索永远不会匹配字符串的内容时停顿.

As far as I am concerned, all calls to scanf to standard I/O terminate with the press of the enter key, so there is no need to include the newline in the specifier string. In fact, this redundancy will only cause the program to stall in search of something that will never match the string.

有没有人可以澄清 scanf 函数的技术细节来解决这个问题?

Is there anyone who can clarify the technicalities of the scanf function to put this problem to rest?

推荐答案

我不相信这个对 scanf 的调用会终止.

I don't believe that this call to scanf would ever terminate.

"54321\n" 这样的 6 个字符输入不足以导致此 scanf("%d\n", &x); 返回.程序停止.还必须发生其他事情.

6 character input like "54321\n" is insufficient to cause this scanf("%d\n", &x); to return. The program stalls. Something else must yet occur.

'\n' 指示 scanf() 使用空格并这样做直到

'\n' directs scanf() to consume white-spaces and to do so until

  1. 检测到非空白.

  1. a non-white-space is detected.

stdin 已关闭

stdin 出现输入错误(罕见).

An input error occurs on stdin (rare).

由于 stdin 通常是 line 缓冲的,scanf() 以块的形式接收数据.

As stdin is usually line buffered, scanf() receives data in chunks.

第一个chunk 123回车不够导致scanf("%d\n", &x); 返回.需要满足以上 3 种情况之一.

The first chunk 123Enter is not enough to cause scanf("%d\n", &x); to return. One of the 3 above needs to happen.

任何以下带有一些非空白的输入都满足#1,无论是:
456回车
xyz回车
回车回车$回车或...

Any following input with some non-white-space fulfills #1, be it:
456Enter or
xyzEnter or
EnterEnter$Enter or ...

然后 scanf() 将返回一个 1 表示一个值,123,被存储在 x 中.上面的 4x$ 是检测到的导致完成的非空白.该字符将是 stdin 上后续输入读取的下一个字符.

Then scanf() will return with a 1 indicate a value, 123, was stored in x. The 4, x or $ above was the non-white-space detected that caused completion. That character will be the next character read by subsequent input on stdin.

scanf("%d\n", &x); 几乎可以肯定是错误的代码,因为它需要另一行 用户输入并且不会检查它的返回值.

scanf("%d\n", &x); is almost certainly the wrong code to use as it obliges another line of user input and does not check its return value.

这篇关于c 中的 scanf 和换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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