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

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

相关推荐
虾球xz5 分钟前
游戏引擎学习第281天:在房间之间为摄像机添加动画效果
c++·人工智能·学习·游戏引擎
扶尔魔ocy14 分钟前
【Linux C/C++开发】轻量级关系型数据库SQLite开发(包含性能测试代码)
linux·数据库·c++·sqlite
ptu小鹏16 分钟前
list重点接口及模拟实现
数据结构·c++·list
__BMGT()1 小时前
C++ QT 打开图片
前端·c++·qt
顾子茵1 小时前
c++从入门到精通(五)--异常处理,命名空间,多继承与虚继承
开发语言·c++
YueiL3 小时前
基于RK3588的智慧农场系统开发|RS485总线|华为云IOT|node-red|MQTT
c++·物联网·华为云·rk3588·rs485
二进制人工智能3 小时前
【OpenGL学习】(二)OpenGL渲染简单图形
c++·opengl
Dream it possible!3 小时前
LeetCode 热题 100_寻找重复数(100_287_中等_C++)(技巧)(暴力解法;哈希集合;二分查找)
c++·leetcode·哈希算法
丶Darling.4 小时前
Day119 | 灵神 | 二叉树 | 二叉树的最近共公共祖先
数据结构·c++·算法·二叉树
醍醐三叶5 小时前
C++文件操作--2 二进制文件操作
开发语言·c++