With reading a keyboard number without using the "enter" in C ++

1

I want to create a menu where the user chooses the option 1 to 5, would like the user to type the number and the program would enter the option without having to press Enter .

Here's 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 opc without the user having to enter Enter and automatically fall into switch-case .

    
asked by anonymous 13.11.2017 / 18:04

1 answer

1

Basically use get() of stream of entry. It is the one that takes a character without waiting for others or a key that finishes.

#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');
}

See running on ideone . And no Coding Ground . Also I put GitHub for future reference .

It's a shame that this code mixes things from C. I gave an organized one.

    
13.11.2017 / 18:37