C++关于输入数字的问题

来源:百度知道 编辑:UC知道 时间:2024/07/07 10:11:08
运行如下代码
#include <iostream>
using namespace std;
int win=0;
int lose=0;

int abs(int n)
{
int ab=(n>0?n:-n);
return ab;
}

main()
{
cout<<"In this game, you are supposed to guess a random number.";
cout<<"if your guess is no 1/6 of the range further from the answer,it'll say hot.";
cout<<"if your guess is no 1/6 of the range further from the answer,it'll say warm.";
cout<<"otherwise,cold"<<endl;
start:
cout<<"select the difficulty level, 1 easiest, 2 medium, 3 hardest";
int level,x;
cin>>level;
switch(level)
{
case 1:
x=6;
break;
case 2:
x=9;
break;
case 3:
x=12;
break;

包含cstdio头文件


int level,x;
cin>>level;
switch(level)
{
case 1:
x=6;
break;
case 2:
x=9;
break;
case 3:
x=12;
break;
default:
cout<<"hey!man! told you to input number 1-3~!";
goto start;
break;
}

改为如下形式:

char level;
int x;
cin>>level;
fflush(stdin);//刷新缓冲区
switch(level)
{
case '1':
x=6;
break;
case '2':
x=9;
break;
case '3':
x=12;
break;
default:
cout<<"hey!man! told you to input number 1-3~!";
goto start;
break;
}

***************************************

刷新缓冲区是为了不让遗留在缓冲区中的内容影响后面的读取。

cin>>ans也可以参照上面的方法修改!

用字符形式处理

char level;
cin>>level;
.
.
.
case '1':
...
case '2':
...
case '3