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

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

相关推荐
mmz12074 分钟前
深度优先搜索DFS2(c++)
c++·算法·深度优先
6Hzlia4 分钟前
【Hot 100 刷题计划】 LeetCode 169. 多数元素 | C++ 哈希表基础解法
c++·leetcode·散列表
暴力求解7 分钟前
C++ ---string类(三)
开发语言·c++
say_fall28 分钟前
有关算法的简单数学问题
数据结构·c++·算法·职场和发展·蓝桥杯
m0_716765231 小时前
数据结构--顺序表的插入、删除、查找详解
c语言·开发语言·数据结构·c++·学习·算法·visual studio
say_fall1 小时前
滑动窗口算法
数据结构·c++·算法
落羽的落羽1 小时前
【算法札记】练习 | Week1
linux·服务器·c++·人工智能·python·算法·机器学习
c++圈来了个新人1 小时前
C++类和对象(上)
c语言·开发语言·数据结构·c++·考研
️是781 小时前
信息奥赛一本通(4005:【GESP2306一级】时间规划)
数据结构·c++·算法
tankeven1 小时前
HJ174 交换到最大
c++·算法