c++ 获取输入

获取键盘输入

cpp 复制代码
#include <iostream>
#include <limits>

bool enter_state(int &pos)
{
    unsigned int userInput;
    std::cout << "[info] 请选择: 0.主驾, 1.副驾, 2.后排" << std::endl;
    std::cout << "[info] 请输入:";
    std::cin >> userInput;

    if (std::cin.fail())
    {
        std::cin.clear();                                                   // 清除错误状态
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 忽略之前的输入缓冲
        std::cout << "Invalid input. Please enter an integer." << std::endl;
        return false;
    }

    if (userInput < 3)
    {
        pos = userInput;
        return true;
    }

    return false;
}

bool enter_feel(int &pos)
{
    unsigned int userInput;
    std::cout << "[info] 请输入驾驶id[" << pos << "]的热感受:";
    std::cin >> userInput;

    if (std::cin.fail())
    {
        std::cin.clear();                                                   // 清除错误状态
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 忽略之前的输入缓冲
        std::cout << "Invalid input. Please enter an integer." << std::endl;
        return false;
    }
    std::cout << "驾驶id[" << pos << "]的热感受:"<<userInput << std::endl;
    return true;
}

int main()
{
    int position = 0;
    while (true)
    {
        if (enter_state(position))
        {
            while (!enter_feel(position))
            {
                /* code */
            }
            
        }
    }
    return 0;
}

红色方框内代码块必须紧跟随,中间插入其他代码,无效

相关推荐
xiaolongmeiya8 分钟前
P3810 【模板】三维偏序 / 陌上花开 cdq分治+树状数组
c++·算法
Chrikk11 分钟前
基于 RAII 的分布式通信资源管理:NCCL 库的 C++ 封装
开发语言·c++·分布式
阿沁QWQ14 分钟前
C++哈希表设计
开发语言·c++·散列表
Yu_Lijing29 分钟前
基于C++的《Head First设计模式》笔记——策略模式
c++·笔记·设计模式
鸿儒51734 分钟前
记录一个C++操作8位影像的一个bug
开发语言·c++·bug
脏脏a34 分钟前
深度剖析 C++ string:从 0 到 1 的模拟实现与细节解析
开发语言·c++
福尔摩斯张35 分钟前
【实战】C/C++ 实现 PC 热点(手动开启)+ 手机 UDP 自动发现 + TCP 通信全流程(超详细)
linux·c语言·c++·tcp/ip·算法·智能手机·udp
罗湖老棍子36 分钟前
【例3-3】医院设置(信息学奥赛一本通- P1338)
数据结构·c++·算法·
历程里程碑1 小时前
C++ 4:内存管理
java·c语言·开发语言·数据结构·c++·笔记·算法
LXS_3571 小时前
Day17 C++提高 之 类模板案例
开发语言·c++·笔记·算法·学习方法