如何在 C++ 中检测'Enter Key'?

how to detect 'Enter Key' in c++?

本文关键字:Key Enter 检测 C++      更新时间:2023-10-16

我想检测按下回车键中断循环。如果用户连续按 2 进入,循环中断。我正在使用矢量来存储用户输入。所有变量的类型都是整数。

#include <iostream>
#include <vector>
using namespace std;
int main()
{   int buffer;
    vector<int> frag;
    do
    {
        cin >>buffer;
        frag.push_back(buffer);
    }while(frag.end()!='n');

}

如何从错误消息中转义"与'运算符!='不匹配(操作数类型为'std::vector::iterator....."?

您可以将std::cin.getn进行比较:

std::vector<int> vecInt;
char c;
while(std::cin.peek() != 'n'){
    std::cin.get(c);
    if(isdigit(c))
        vecInt.push_back(c - '0');
}
for (int i(0); i < vecInt.size(); i++)
    std::cout << vecInt[i] << ", ";
The input : 25uA1 45p
The output: 2, 5, 1, 4, 5,
  • 如果要读取两个整数值,则在第二次按Enter键后,它将停止读取:

    std::vector<int> vecInt;
    int iVal, nEnterPress = 0;
    
    while(nEnterPress != 2){
        if(std::cin.peek() == 'n'){
            nEnterPress++;
            std::cin.ignore(1, 'n');
        }
        else{
            std::cin >> iVal;
            vecInt.push_back(iVal);
        }
    }
    for (int i(0); i < vecInt.size(); i++)
        std::cout << vecInt[i] << ", ";
    Input:  435  (+ Press enter )
            3976 (+ Press enter)
    Output: 435, 3976,