C++ cin 问题
好的,我正在编写一个简单的 C++ 函数来组合 cin'd 字符串。我目前正在 Linux 上工作,所以我没有简单的“getline(cin, input)”命令。这是到目前为止的代码:
string getLine()
{
string dummy;
string retvalue;
do
{
cin << dummy;
retvalue += dummy;
} while
return retvalue;
}
我想知道的是:提示实际上是在要求用户输入,还是仍在从由于空格而留下的缓冲区中读取?
Okay, I was writing a simple C++ function to combine cin'd strings. I'm working on Linux at the moment, so I don't have the luxury of a simple "getline(cin, input)" command. Here's the code so far:
string getLine()
{
string dummy;
string retvalue;
do
{
cin << dummy;
retvalue += dummy;
} while
return retvalue;
}
What I want to know is this: is the prompt actually asking the user for input, or is it still reading from the buffer that was left over because of a space?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为
strings
定义了一个getline
:There is a
getline
defined forstrings
:Linux 与它有什么关系?
getline
是标准 C++,只不过拼写为cin.getline(input, size[, delimiter])
。编辑:不删除它,因为它是一个有用的参考,但对于想要
std::string
的人来说,AraK 的帖子说明std::getline
应该是首选代码>.istream
的getline
工作在char *
上。What's Linux got to do with it?
getline
is standard C++, except it's spelledcin.getline(input, size[, delimiter])
.Edit: Not deleting this because it's a useful reference, but AraK's post illustrating
std::getline
should be preferred for people who want astd::string
.istream
'sgetline
works on achar *
instead.是的。提示实际上是要求用户输入,但它期望的是一个单词而不是一行。这可能就是它对你显得空间敏感的原因。
假设您想阅读不止一行,您想要的就是这样。
该代码还有一些其他问题。
问题中的循环更接近单词阅读器。
这将有助于实现该目标。
Yes. the prompt IS actually asking the user for input, but it is expecting a word rather than a line. That is possibly why it appeared space sensitive to you.
What you want, assuming you want to read more than one line, is this.
The code had a few other issues.
The loop in the question is closer to a word reader.
This would do for that objective.
getline()
位于
标头中,我总是忘记这一点。
getline()
is in the<string>
headerI always forget that.