使用EOF获取所有用户输入?

发布于 2025-01-26 23:17:06 字数 385 浏览 3 评论 0原文

我有问题从终端获取所有用户输入。这总是短的一行,这是最后一行。

do{
    getline(std::cin, input);
    buffer += input;
    buffer += '\n';
}while(!input.empty());

给我所需的输出,但是当我按Enter时结束,当我按CTRL+D时,我希望它到达文件末端(EOF)时结束。我已经尝试过

while(!(std::cin >> input).eof()){
    buffer += input;
    buffer += '\n';
}

,但没有得到最后一行。在while-loop之后,将输入添加到缓冲区也无法解决。

I'm having problems getting all the user input from the terminal. It's always one line short, and it's the last line.

do{
    getline(std::cin, input);
    buffer += input;
    buffer += '\n';
}while(!input.empty());

gives me the desired output, but it ends when I press Enter, and I want it to end when it reaches End Of File(EOF), when i press Ctrl+D. I have tried

while(!(std::cin >> input).eof()){
    buffer += input;
    buffer += '\n';
}

but it doesn't get the last line. Adding the input to the buffer after the while-loop also doesn't solve it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鸠魁 2025-02-02 23:17:06

继续阅读输入, getline getline

std::string buffer;
std::string input;

while (std::getline(std::cin, input))
{
    buffer += input;
    buffer += '\n';
}

:您输入eof getline 将设置eofbit ,循环将结束。

无论如何,第二片片段也应存储最后一个输入。

Keep reading input with getline:

std::string buffer;
std::string input;

while (std::getline(std::cin, input))
{
    buffer += input;
    buffer += '\n';
}

When you input EOF getline will set eofbit and the loop will end.

In any case the second snippet should store the last input as well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文