cin命令为什么在缓冲区中留下一个“ \n”? [英] Why does cin command leaves a '\n' in the buffer?

查看:137
本文介绍了cin命令为什么在缓冲区中留下一个“ \n”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与以下内容有关: cin和getline跳过输入,但是它们不相关回答为什么会发生以及如何解决。

This is related to: cin and getline skipping input But they don't answer the why it happens just the how to fix it.

为什么 cin 会留下'\n'

Why does cin leaves a '\n' in the buffer but just cin.getline takes it?

例如:

cin >> foo;
cin >> bar;//No problem
cin >> baz;//No problem.

但是使用 cin.getline

cin >> foo;
cin.getline(bar,100);//will take the '\n'

那为什么为什么 cin 不会发生,而为什么 cin.getline 会发生呢?

So why it doesn't happen with cin but it does with cin.getline?

推荐答案

因为,当您说 getline 时,您说要获得一行...一行是以 \n 结尾的字符串,结尾是其中的一部分。

Because, when you say getline you say you want to get a line... A line is string that ends with \n, the ending is integral part of it.

cin>>东西,您想要得到东西,仅此而已。终端标记不是它的一部分,因此不会消耗。除非您对行有特殊的类型,但是标准库中没有这样的东西。

When you say cin >> something, you want to get precisely something, nothing more. End-line marker is not part of it, so it's not consumed. Unless you would have a special type for line, but there is no such thing in standard library.

尽管没有标准引用,这可以被视为观点,但这是背后的逻辑。 它们具有不同的语义 getline 还有另一个区别用作未格式化的输入 operator>> 用作格式化输入。我强烈建议阅读这些链接以获取不同之处。这也说明它们在语义上是不同的。

While without citations from standard this might be taken as opinion, but this is logic behind it. They have different semantics. There is also another difference getline works as unformatted input, and operator>> works as formatted input. I strongly suggest reading of those links to get the differences. This also says that they are semantically different.

另一个答案(更好或更不值得商de)是引用标准,我敢肯定地说, getline 的行为,以及 operator>> 对于不同类型的行为,并说,它的工作原理是这样的,因为standard这样说。这会很好,因为该标准绝对定义了事物的工作方式,并且可以任意地进行工作……而且它很少解释设计背后的动机和逻辑。

Another answer, better or not is debatable, would be to quote standard, that I am sure says, how getline behaves, and how operator>> behaves for different types, and say, it works like this, because standard says so. This would be good, because the standard absolutely defines how things work and it can do so arbitrarily... And it rarely does explain motivation and logic behind the design.

这篇关于cin命令为什么在缓冲区中留下一个“ \n”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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