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

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

相关推荐
炸膛坦客4 小时前
单片机/C/C++八股:(二十)指针常量和常量指针
c语言·开发语言·c++
炸膛坦客5 小时前
单片机/C/C++八股:(十九)栈和堆的区别?
c语言·开发语言·c++
2401_831824966 小时前
代码性能剖析工具
开发语言·c++·算法
是wzoi的一名用户啊~6 小时前
【C++小游戏】2048
开发语言·c++
Sunshine for you7 小时前
C++中的职责链模式实战
开发语言·c++·算法
qq_416018727 小时前
C++中的状态模式
开发语言·c++·算法
2401_884563247 小时前
模板代码生成工具
开发语言·c++·算法
2401_831920748 小时前
C++代码国际化支持
开发语言·c++·算法
m0_672703318 小时前
上机练习第51天
数据结构·c++·算法
2401_851272998 小时前
自定义内存检测工具
开发语言·c++·算法