How to read a keyboard number without using "enter" in C++

Asked

Viewed 1,216 times

1

I want to create a menu in which the user chooses the option 1 to 5, I would like the user to type the number and the program to enter the option without pressing Enter.

Follow an example

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
struct pessoa {
    int ID;
    string nome [20];
    string tel [20];
};
typedef struct pessoa P;
int main () {
    int vet[10]={0,0,0,0,0,0,0,0,0,0};
    int opc;    
    do{
    cout<<"[0] incluir pessoa"<<endl;
    cout<<"[1] Alterar pessoa"<<endl;
    cout<<"[2] Excluir pessoa"<<endl;
    cout<<"[4] Recuperar pessoa"<<endl;
    cout<<"[5] Sair"<<endl;
    cin>>opc;
    switch (opc){
        case '0':
        break;
        case '1':
        break;  
        case '2':
        break;
        case '3':
        break;
        case '4':
        break;
        case '5':
        break;
        default:
            cout<<"Opção Invalida"<<endl;   
    }
    }while(opc != 5);

    return 0;
}

I want to read the opc without the user needing to enter the Enter and automatically fall into the switch-case.

1 answer

1


Basically use the get() of stream input. It is he who picks up a character without waiting for others or a key that ends.

#include <iostream>
#include <string>
using namespace std;

struct Pessoa {
    int ID;
    string nome;
    string tel;
}; //isto provavelmente deveria ser uma classe

int main() {
    Pessoa pessoa; //provavelmente deveria ser inicializado por referência e alocado dinamicamente
    char opc = 'z';
    do {
        cout << "[1] incluir pessoa" << endl;
        cout << "[2] Alterar pessoa" << endl;
        cout << "[3] Excluir pessoa" << endl;
        cout << "[4] Recuperar pessoa" << endl;
        cout << "[0] Sair" << endl;
        opc = cin.get();
        switch (opc) {
            case '0':
                break;
            case '1':
                cout << "1" << endl;
                break;  
            case '2':
                cout << "2" << endl;
            break;
            case '3':
                cout << "3" << endl;
                break;
            case '4':
                cout << "4" << endl;
                break;
            default:
                cout << "Opção Invalida" << endl;
        }
    } while (opc != '0');
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

It’s a shame this code mixes things from C. I gave an organized.

  • Thank you very much, I am in the second semester of S.I and really still very amateur my codes, but what would Typedef for Struct?? When calling it in a function I will use type Cin>>Person.name??

  • I switched to get more C++ and to show how to declare. As this was not in the original question it is not part of the scope of this, but it is almost this yes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.