You need to enable JavaScript to run this app. C++图书管理程序如何通过conio.h或替代方案实现键盘输入交互
优惠活动
大模型
产品
解决方案
定价
更多

C++图书管理程序如何通过conio.h或替代方案实现键盘输入交互

C++图书馆程序键盘交互实现方案

一、Windows平台(基于conio.h)实现

直接使用conio.h提供的_getch()函数即可实现无回车的键盘输入捕获,修改后的完整代码如下:

#include <iostream>
#include <conio.h>
#include <vector> // 用于存储所有图书,后续查找功能需要
#include <string>

using namespace std;

class Book {
public:
    string title; 
    string sepnum; // 原double类型优化为string,保留前导零,避免精度问题
};

// 全局存储所有图书,也可以封装到管理类中,这里做简化实现
vector<Book> bookList;

void AddMenu() {
    Book book1;
    cout << "\n********ADD MENU********" << endl;
    cout << "Enter Book Name:" << endl;
    cin >> book1.title;
    cout << "Enter Book Callsign (Ex: 0001, 5672):" << endl;
    cin >> book1.sepnum;
    bookList.push_back(book1); // 将新增图书存入全局列表
    cout << "Succesfully added" << endl;
    cout << "************************\n" << endl;
}

void FindMenu() {
    // 此处补充查找逻辑,比如输入编号/书名匹配bookList中的条目
    cout << "\n********FIND MENU********" << endl;
    cout << "Find function to be implemented" << endl;
    cout << "************************\n" << endl;
}

int main()
{
    char key;
    while (true) {
        cout << "**********MENU**********" << endl;
        cout << "1. Add Book" << endl;
        cout << "2. Find Book" << endl;
        cout << "q. Exit Program" << endl;
        cout << "************************" << endl;

        key = _getch(); // 捕获键盘输入,无需用户按回车确认
        if (key == '1') {
            AddMenu();
        } else if (key == '2') {
            FindMenu();
        } else if (key == 'q' || key == 'Q') {
            cout << "Exiting program..." << endl;
            break;
        } else {
            cout << "Invalid input, please press 1/2/q\n" << endl;
        }
    }
    return 0;
}

二、跨平台兼容方案(conio.h替代实现)

如果需要在Linux/macOS系统编译运行,没有原生conio.h可用,可以用以下自定义的getch函数替代,代码如下:

#ifdef _WIN32
#include <conio.h>
#else
#include <termios.h>
#include <unistd.h>
char _getch() {
    struct termios oldt, newt;
    char ch;
    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
    ch = getchar();
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    return ch;
}
#endif

把这段代码加到头文件引入的位置,后续调用_getch()的逻辑不用修改,就能实现全平台兼容的无回车键盘捕获。

三、现有代码优化提示

  • 原代码中sepnum用double类型会丢失编号前导零,且大编号会出现精度丢失,替换为string或int更合理
  • 原AddMenu中的Book对象是局部变量,函数执行完就销毁,后续查找功能无法读取到已添加的图书,用vector<Book>存储所有图书可解决该问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 13:09:00