使用EOF终结器与.empty()函数获取相同的输入
我想获取用户输入,并且给出的字符数很重要。我通过input.empty()
获得了令人满意的结果,但是在我按Enter后终止。我希望它在我专门键入ctrl+d
之后终止。
1) do{ 2) while(std::getline(std::cin, input)){
getline(std::cin, input); buffer += input;
buffer += input; buffer += '\n';
buffer += '\n'; }
}while(!input.empty()); std::cin.ignore();
除了Enter终结器外,第一个代码按照我的要求工作,第二个代码具有更多的字符,我不确定它的确是什么,但是当我键入ctrl+d 。
输入
和缓冲区
均为std :: String
。因此,如何获得与input.empty()
的相同结果。
先感谢您。
I want to get user input, and the number of characters that are given is important. I get a satisfying result with input.empty()
but it terminates after I press Enter. I want it to terminate after i specifically type Ctrl+D
.
1) do{ 2) while(std::getline(std::cin, input)){
getline(std::cin, input); buffer += input;
buffer += input; buffer += '\n';
buffer += '\n'; }
}while(!input.empty()); std::cin.ignore();
Other than the Enter terminator the first code work as I want it to, and the second one has a character more, which I'm not sure what it exactly is, but it does end when I type Ctrl+D
. input
and buffer
are both std::string
. So how can I get the same result as input.empty()
.
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的问题中,您声称第二个代码片段在
buffer
中比第一个代码段产生的字符更多。但是,我认为此语句是错误的。由于以下原因,这是第一个应该具有更多字符的角色:std :: getline
至少读取一个字符后遇到文件结束,那么两个代码段都将表现相同方式。但是,如果
std :: getline
在阅读至少一个字符之前遇到文件结束(即,如果在行开始时遇到了一个字符),则两个代码段的行为是不同的:第一个代码片段将在终止循环之前将附加的newline字符写入buffer
,而第二个代码段将立即终止。换句话说,第一个代码段产生的字符太多,因为它的逻辑是错误的。因此,我建议您使用第二个片段。但是,目前尚不清楚第二个代码段中应该完成的
std :: cin.ignore();
,因为函数std :: getline
已经删除了输入流(如果存在)的newline字符。另外,调用std :: ignore
在已经达到流的结束时可能没有效果。因此,您可能应该删除该线路。In your question, you claim that the second code snippet produces one character more in
buffer
than the first code snippet. However, I assume that this statement is false. It is the first one which should have one character more, for the following reason:When
std::getline
encounters end-of-file after reading at least one character, then both code snippets will behave the same way.However, if
std::getline
encounters end-of-file before reading at least one character (i.e. if it is encountered at the start of the line), then the behavior of the two code snippets is different: The first code snippet will write an additional newline character tobuffer
, before the loop gets terminated, whereas the second code snippet will terminate immediately.In other words, the first code snippet produces one character too much, because its logic is wrong. Therefore, I suggest that you use the second snippet. However, it is unclear what
std::cin.ignore();
in the second code snippet is supposed to accomplish, because the functionstd::getline
has already removed the newline character from the input stream (if it existed). Also, callingstd::ignore
when the end of the stream has already been reached will probably have no effect. Therefore, you should probably remove that line.