写在前面:作为一只小白,感谢小甲鱼老师提供这么好的入门课程。因此在这里做个笔记,如有侵权请联系删除。
www.fishc.com
题目1:这个程序将向用户提出一个“Y/N”问题,然后把用户输入的值赋值给answer变量。
要求:
---针对用户输入的“Y”或“y”和“N”或“n”进行过滤;
---发掘程序可能存在的任何问题,想想为什么?
#include <iostream>
using namespace std;
int main()
{
char answer;
cout << "请问可以格式化您的硬盘吗?![Y/N]" << endl;
cin >> answer;
switch (answer)
{
case 'Y':
case 'y':
cout << "随便格式化硬盘不好" << endl;
break;
case 'N':
case 'n':
cout << "您的选择是明智的!" << endl;
break;
default:
cout << "您的输入不符合要求!!!" << endl;
break;
}
cin.ignore(100, '\n');
cout << "输入任何字符结束程序!" << endl;
cin.get();
return 0;
}
重点内容:
1、为什么要用cin.ignore()
在debug文件下双击运行exe文件时,输入答案后命令窗口一闪而过,这是因为cin.get()接收的是上一次的换行符,实现不了暂停的功能,于是加上cin.ignore(100, '\n'); 接收100个字符后才忽略
题目2: 编写一个"温度单位转换程序",提示用户已【xx.x C】或【xx.x F】的格式输入.
#include <iostream>
using namespace std;
int main()
{
//华氏温度=摄氏温度*9.0/5.0+32
const unsigned short ADD_SUBTRACT = 32; //静态变量
const double RATIO = 9.0 / 5.0;
double tempIn, tempOut;
char typeIn, typeOut;
cout << "请以[xx.x C]或者[xx.x F]格式输入一个温度: " <<endl;
cin >> tempIn >>typeIn;
cin.ignore(100, '\n');
cout <<endl;
switch (typeIn)
{
case 'C':
case 'c':
tempOut = tempIn * RATIO + ADD_SUBTRACT;
typeOut = 'F';
typeIn = 'C';
break;
case 'F':
case 'f':
tempOut = (tempIn - ADD_SUBTRACT) / RATIO;
typeOut = 'C';
typeIn = 'F';
break;
default:
typeOut = 'E';
break;
}
if (typeOut != 'E')
{
cout << tempIn << typeIn
<< " = " << tempOut
<< typeOut << endl;
}
else
{
cout << "输入错误!" << endl;
}
cout << "请输入任何字符结束程序!" << endl;
cin.get();
return 0;
}
对输入数据进行合法性检查:
对输入数据进行合法性检查的具体做法取决于具体的变量类型和它们的取值范围.
解决这些问题的办法之一就是对cin调用的结果不要做任何假设,cin对象有几个专门用来报告情况的成员函数,
它们将返回一个真假值来表明cin的状态
----eof() 如果到达文件(或输入)末尾,返回true
----fail() 如果cin无法工作,返回true
---bad() 如果cin因为比较严重的原因(例如内存不足)而无法工作,返回true
---good() 如果以上情况都没发生,返回true