首页 > 解决方案 > 如何在 C++ 上使用 Ctrl + D 结束用户的输入

问题描述

(我在 Windows 上使用 VS Code)

我正在尝试从用户那里获取多行输入,并且当用户点击“Ctrl + D”时输入必须结束,然后它必须继续进入其余代码

#include <iostream>
using namespace std;
int main()
{

string x, input, output, choice;

cin >> x;
cin >> choice:

getline(cin , input) ;                // need this part to end when user hits Ctrl + D and i 
                                         need more than one line of input

// Rest of my code already completed 

}

标签: c++visual-studio-code

解决方案


Ctrl D 对应于 ASCII 字符 EOT,其十进制值为 4。因此,
getline(cin, input, '\x04');
这适用于多行,getline 将在您执行 Ctrl D 然后输入后返回,剥离 Ctrl D 以及您在输入之前输入的任何内容。


推荐阅读