【问题标题】:how to detect 'Enter Key' in c++?如何在 C++ 中检测“输入键”?
【发布时间】:2017-10-11 14:33:11
【问题描述】:

我想检测 Enter 按下以打破循环。 如果用户按 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');


}

如何摆脱错误信息 “'operator!=' 不匹配(操作数类型是 'std::vector::iterator.....”?

【问题讨论】:

标签: c++ vector iterator integer


【解决方案1】:

您可以将std::cin.get\n 进行比较:

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,
    

【讨论】:

  • 谢谢,但我需要整数类型,而不是向量的字符
  • 它只需要一个输入。我需要多个输入,直到两个输入。
  • I need multiple input until two enters 你的意思是用“两个”“双击”进入停止阅读或者你的意思是直到字符 2 进入?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-10
  • 2017-11-23
  • 1970-01-01
  • 2015-02-16
  • 2019-09-16
  • 2014-04-18
相关资源
最近更新 更多