问题描述
这与: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
会在缓冲区中留下一个 '
' 而只有 cin.getline 接受它?
Why does cin
leaves a '
' 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 '
'
那么为什么 cin
不会发生这种情况,而 cin.getline
会发生这种情况?
So why it doesn't happen with cin
but it does with cin.getline
?
推荐答案
因为,当你说 getline
时,你说你想要得到一行...一行是以
,结尾是其中不可或缺的一部分.
Because, when you say getline
you say you want to get a line... A line is string that ends with
, the ending is integral part of it.
当你说 cin >>东西
,你想要精确地获得something
,仅此而已.结束线标记不是它的一部分,所以它不会被消耗.除非你有一个特殊的 line 类型,但标准库中没有这样的东西.
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.
另一个答案,无论好坏是有争议的,将引用标准,我肯定会说,getline
的行为方式,以及 operator>>
的行为方式不同的类型,比如说,它是这样工作的,因为标准是这样说的.这会很好,因为该标准绝对定义了事物的工作方式,并且可以任意执行......而且它很少解释设计背后的动机和逻辑.
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 命令会在缓冲区中留下一个 ' '?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!