【C++】【学习笔记】【005】输入输出小结

对输入数据进行合法性检查:cin对象有几个专门用来报告其工作情况的成员函数,它们将返回一个真/假值来表明cin的状态。
cin的成员函数 作用
cin.eof()
如果到达文件(或输入)末尾,则返回true。
cin.fail()
如果cin无法工作,则返回true。
cin.bad()
如果cin因为比较严重的原因(例如:内存不足)而无法工作,则返回true。
cin.good()
如果以上情况都没有发生,则返回true。

题目:写一个程序,向用户剔除一个“Y/N”问题,然后把用户输入的值付给answer变量。
要求:针对用户输入'Y'或'y'和‘N’或‘n’进行过滤。

#include <iostream>

int main()
{
    char answer;
    std::cout << "Do you like her?(Y/N)";

    while (1)
    {
        std::cin >> answer;
        if (answer != 'Y' && answer != 'y' && answer != 'N' && answer != 'n')
        {
            std::cout << "Input error. please input (Y/N).";
            continue;
        }
        else
        {
            break;
        }
    }
    std::cout << "Your input is: " << answer << std::endl;

    std::cin.ignore(100, '\n'); // 清空键盘缓冲区
    std::cin.get();

    return 0;
}

题目:编写一个温度单位转换程序,提示用户以【xx.x C】或【xx.x F】的格式输入。
要求:如果用户输入的是32.4 C,程序将自动转换为90.32 F输出;反之,如果用户输入的是90.32 F,程序将自动转换为34.2 C输出。

// 温度单位转换
// 华氏温度 = 摄氏温度 * 9.0 / 5.0 + 32
// 摄氏温度 = (华氏温度 - 32) * 5.0 / 9.0

#include <iostream>

int main()
{
    float num;
    char unit;
    const unsigned short ADD_SUBTRACT = 32;
    const double RATIO = 9.0 / 5.0;
    std::cout << "Please input degree. Format: [xx.x C] or [xx.x F]: ";
    while (1)
    {
        std::cin >> num >> unit;
        if (unit == 'C' || unit == 'c' || unit == 'F' || unit == 'f')
        {
            break;
        }
        std::cout << "Input error. Please input again.\n";
    }
    if ('C' == unit || unit == 'c')
    {
        num = num * RATIO + ADD_SUBTRACT;
        unit = 'F';
    }
    else
    {
        num = (num - ADD_SUBTRACT) / RATIO;
        unit = 'C';
    }
    std::cout << num << " F" << "\n";
    return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值