C++检测输入是否是整数

来源:互联网 发布:阿尔法复制软件 编辑:程序博客网 时间:2024/06/07 12:06

学校一道zz题但是检测合法性输入这里费了好大功夫。

1、 猜价格游戏

编写C++程序完成以下功能:

(1) 假定有一件商品,程序用随机数指定该商品的价格(1-1000的整数);

(2) 提示用户猜价格,并输入:若用户猜的价格比商品价格高或低,对用户作出相应的提示;

(3) 直到猜对为止,并给出提示。

(提示及要求:1,要求使用C++的输入输出方式(cin, cout),不能使用C语言的printf等;2,注意检查输入的

目前想到的异常情况有:

1.分数

2.字符

3.数字字符混合

有的同学选择的是先用字符存储,然后逐个分析。这很直接也很简单。

参考代码:

#include <iostream>
#include<time.h>
using namespace std;


bool isint(char s[])
{
for (int i = 0; s[i] != '\0'; i++)
if (!isdigit(s[i]))
return false;
return true;
}
int main()
{
srand((int)time(NULL));
int price = rand() % 1000 + 1;//生成1-1000的随机数
char input[100];
int guess = 0;


cout << "Please input your prediction(integer:1-1000):\n";
while (guess != price)
{
while (cin >> input&&!isint(input))
{
cout << "Please input an integer(1-1000)!\n\n";
getchar(); 
}
guess = atoi(input);
if (guess < price)
cout << "too low\n";
else if (guess > price)
cout << "too high\n";
}
cout << "Right!\n";
system("pause");
return 0;
}

我的方法是:将要读入的数字先设为0,如果输入的是字符,cin会什么都读不进去,数字仍然为0,这样不符合1-1000的范围,就会进入错误提示。

注意cin是从缓冲区读入,如果没有清空缓冲区的操作,会不停地从有错误信息的缓冲区读入。需要cin.clear()。(这时缓冲区里存的可能就是读入的错误输入吧…………不知道怎么看啊…………)

检测小数就用guess != (int)guess就好

还有一个小问题是吞掉已有的错误输入,试过cin.getline,getline都不行,可能是因为cin之后光标已经在下一行了。只能用getchar读入数据(不知道为啥啊!)

代码:

#include <iostream>
#include<time.h>
using namespace std;


int main()
{
srand((int)time(NULL));
int price = rand() % 1000 + 1;//生成1-1000的随机数
float guess = 0;


cout << "Please input your prediction(integer:1-1000):\n";
while (guess != price)
{
char ch;
cin >> guess;
if (guess > 1000 || guess < 1|| guess != (int)guess||(ch=getchar())!='\n')
{
while ((ch = getchar()) != '\n');//吞掉所有的错误输入
cin.clear();//清空输入缓冲区
cout << "Please input an integer(1-1000)!\n\n";
}
else if (guess < price)
cout << "too low\n"; 
else if (guess > price)
cout << "too high\n"; 
guess = 0;
}
cout << "Right!\n";
system("pause");
return 0;
}

反正第二个方法纯粹是自己想试试新的方法,结果发现一大堆问题以后的产物。

原创粉丝点击