You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++学生信息管理程序的if-else语句中读取Esc按键并兼容其他输入

Hey there! I get that you're trying to add an Esc-key exit to your student management program, and you want it to play nicely with all the existing input operations. As a beginner, this is a great problem to tackle—let's walk through how to make this work.

Core Idea

The main issue here is that cin blocks your program while waiting for input, so we can't just check for the Esc key with it alone. Since you're already including conio.h, we can use two functions from that header to fix this:

  • _kbhit(): Checks if a key has been pressed without blocking the program (returns non-zero if a key is waiting)
  • _getch(): Reads the pressed key immediately, without waiting for Enter (and it doesn't echo the key to the console)

We'll modify your main loop to check for the Esc key before handling the menu input, and also clean up the input buffer to avoid weird behavior from leftover characters.

Modified Full Code

#include <bits/stdc++.h>
#include <conio.h>
using namespace std;

class Node {
public:
    int roll;
    string Name;
    string address;
    int contact;
    string email;
    Node* next;
};

Node* head = new Node();

bool check(int x) {
    if (head == NULL)
        return false;
    Node* t = head;
    while (t != NULL) {
        if (t->roll == x)
            return true;
        t = t->next;
    }
    return false;
}

void Insert_Record(int roll, string Name, string address, int contact, string email) {
    if (check(roll)) {
        cout << "Student with this record Already Exists\n";
        return;
    }
    Node* t = new Node();
    t->roll = roll;
    t->Name = Name;
    t->address = address;
    t->contact = contact;
    t->email = email;
    t->next = NULL;
    if (head == NULL || (head->roll >= t->roll)) {
        t->next = head;
        head = t;
    } else {
        Node* c = head;
        while (c->next != NULL && c->next->roll < t->roll) {
            c = c->next;
        }
        t->next = c->next;
        c->next = t;
    }
    cout << "Record Inserted Successfully\n";
}

void Search_Record(int roll) {
    if (!head) {
        cout << "No such Record Available\n";
        return;
    } else {
        Node* p = head;
        while (p) {
            if (p->roll == roll) {
                cout << "Roll Number\t" << p->roll << endl;
                cout << "Name\t\t" << p->Name << endl;
                cout << "Address\t" << p->address << endl;
                cout << "Contact\t\t" << p->contact << endl;
                cout << "Email\t\t" << p->email << endl;
                return;
            }
            p = p->next;
        }
        cout << "No such Record Available\n";
    }
}

int Delete_Record(int roll) {
    Node* t = head;
    Node* p = NULL;
    // Deletion at Begin
    if (t != NULL && t->roll == roll) {
        head = t->next;
        delete t;
        cout << "Record Deleted Successfully\n";
        return 0;
    }
    // Deletion Other than Begin
    while (t != NULL && t->roll != roll) {
        p = t;
        t = t->next;
    }
    if (t == NULL) {
        cout << "Record does not Exist\n";
        return -1;
    }
    p->next = t->next;
    delete t;
    cout << "Record Deleted Successfully\n";
    return 0;
}

void Show_Record() {
    Node* p = head;
    if (p == NULL) {
        cout << "No Record Available\n";
    } else {
        cout << "Roll-No\tName\tAddress\tContact\tEmail \n";
        while (p != NULL) {
            cout << p->roll << "\t\t" << p->Name << "\t\t" << p->address << "\t\t" << p->contact << "\t\t" << p->email << endl;
            p = p->next;
        }
    }
}

int main() {
    head = NULL;
    string Name, address, email;
    int Roll, contact;
    while (true) {
        cout << "\n\t\tWelcome \n\n\tPress\n\t1 to Store New Data\n\t2 To Search the Record\n\t3 To Delete a Data\n\tPress Escape Key to Exit\n";
        cout << "\nEnter your Choice\n";

        // Check if any key is pressed
        if (_kbhit()) {
            int key = _getch();
            // Esc key has ASCII code 27
            if (key == 27) {
                cout << "\nExiting program...\n";
                break;
            }
            // If the key is a digit, put it back into input buffer so cin can read it
            else if (isdigit(key)) {
                cin.putback(static_cast<char>(key));
            }
        }

        // Handle menu choice input
        int Choice;
        cin >> Choice;

        // Handle invalid input (non-digit)
        if (cin.fail()) {
            cout << "Invalid input! Please enter a number or press Esc to exit.\n";
            cin.clear(); // Clear error state
            // Ignore remaining characters in buffer until newline
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            continue;
        }

        switch(Choice) {
            case 1:
                cout << "Enter Roll Number of Student\n";
                cin >> Roll;
                cout << "Enter Name of Student\n";
                cin >> Name;
                cout << "Enter The Address of Student \n";
                cin >> address;
                cout << "Enter Contact of Student\n";
                cin >> contact;
                cout << "Enter Email Address of the Student\n";
                cin >> email;
                Insert_Record(Roll, Name, address, contact, email);
                break;
            case 2:
                cout << "Enter Roll Number of Student whose record you want to Search\n";
                cin >> Roll;
                Search_Record(Roll);
                break;
            case 3:
                cout << "Enter Roll Number of Student whose record is to be deleted\n";
                cin >> Roll;
                Delete_Record(Roll);
                break;
            default:
                cout << "Invalid Choice! Try Again\n";
                // Clear any leftover input
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
    }
    return 0;
}

Key Changes Explained

  1. Esc Key Detection: We added _kbhit() to check if a key is pressed before reading the menu choice. If the key is 27 (Esc's ASCII code), we print a message and break out of the loop to exit.
  2. Handling Digit Input: If the pressed key is a digit, we use cin.putback() to put it back into the input buffer so cin can read it normally—this keeps your existing menu input working as expected.
  3. Invalid Input Handling: We added checks for cin.fail() to catch non-digit inputs, clear the error state, and ignore leftover characters to prevent infinite loops.
  4. Menu Fix: I noticed your original menu had a typo (option 3 was missing in the prompt but present in code), so I fixed that to match the actual functionality.

This way, you can either enter a menu number as before, or press Esc at any time to exit the program smoothly.

内容的提问来源于stack exchange,提问作者saurabh singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 06:12:46