C++输入输出小练习

//C++输入输出

//向用户提出一个“y/N”问题
//然后把用户输入的值赋给 answer 变量

//针对用户输入'Y''y'和'N''n'进行过滤
#include <iostream>

using namespace std;
int main()
{
    
    
	char answer;
	cout<<"请问可以格式化您的硬盘吗?【Y/N】"<<"\n";
	cin>>answer;
	
	switch(answer)
	{
    
    
		case 'Y':
		case 'y':
			cout<<"可以 测试"<<"\n";break;
		case 'N':
		case 'n':
			cout<<"不可以 测试"<<"\n";break; 
		default:
			cout<<"您的输入不符合要求"<<"\n";break;
	}
	
	return 0;
} 



//编写一个“温度单位转换程序”
//提示用户 以 [xx.x C] 或 [xx.x F]的格式输入
//要求:输入:34.2 C自动转换为90.32 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]的格式输入一个温度:";
	 cin>>tempIn>>typeIn;
	 cin.ignore(100,'\n');
	 cout<<"\n";
	 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<<"\n\n";
	 }
	 else
	 	cout<<"输入错误!,请输入任意字符结束程序"<<"\n\n";
	 	cin.get(); 
	return 0;
} 



//对输入数据进行合法性检查
//不要相信任何程序的输入
//尤其是由用户输入的东西
//这是计算机安防工作的基本原则

//C类语言没有对数组进行检查 :缓冲区溢出 

//cin
//eof():如果到达文件(或输入)末尾,返回true
//fail():如果cin无法工作,返回true 
//bad():如果cin因为比较严重的原因(例如内存不足) 
// 而无法工作,返回 true 
//good() :如果以上情况都没有发生,返回true



猜你喜欢

转载自blog.csdn.net/qq_48167493/article/details/120596602