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;
}

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

相关推荐
殳翰35 分钟前
下服务器端开发流程及相关工具介绍(C++)
开发语言·c++
青瓦梦滋1 小时前
协议定制/序列化-反序列化(Linux视角)
linux·服务器·网络·c++
山登绝顶我为峰 3(^v^)35 小时前
C/C++ 交叉编译方法
java·c语言·c++
郝学胜-神的一滴9 小时前
中级OpenGL教程 013:渲染器类架构设计与逐帧渲染流程详解
开发语言·c++·unity·游戏引擎·图形渲染·opengl·unreal
小小龙学IT10 小时前
C++ 并发编程深度解析:从内存模型到无锁数据结构
数据结构·c++
凯瑟琳.奥古斯特10 小时前
力扣1013三等分解法与C++实现
开发语言·c++·算法·leetcode·职场和发展
一拳一个呆瓜11 小时前
【STL】iostream 编程:缓冲区的作用
c++·stl
我不是懒洋洋11 小时前
从零实现一个分布式任务调度器:XXL-JOB的核心设计
c++
凯瑟琳.奥古斯特12 小时前
力扣1012数位DP解法详解
开发语言·c++·算法·leetcode·职场和发展