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;
}
反正第二个方法纯粹是自己想试试新的方法,结果发现一大堆问题以后的产物。
- C++检测输入是否是整数
- 输入一个整数判断是否是回文
- 判断输入的是否是整数
- 一行c表达式检测无符号整数是否是2的幂
- 检测输入是否全是数字
- 输入一个整数,判断该整数是否是回文!
- [iOS 记录] 检测输入的是否为整数
- 【C】判断一个字符串是否是整数
- 正则表达式-检测是否是数字,包括整数,小数
- 不用trycatch判断用户输入的是否是整数
- 输入一个整数,判断其是否是2^n,.............................
- 输入一个整数,然后判断是否是回文数
- 异常处理 判断输入的是否是五个整数
- (c++)写一个判断素数的函数,在主函数输入一个整数,输出是否是素数的消息。
- C语言判断输入是否是数字
- 检测输入框中是否是合法的IP地址
- C语言:计算输入的整数是几位数
- 检测是否是虚拟机
- malloc/free 与new/delete的区别
- MySQL中的锁(表锁、行锁)
- 网络编程
- Android判断是否连接网络或者是否打开了GPS
- 哪位明星会是你心目中的“旗袍”代言人?
- C++检测输入是否是整数
- 实验吧 web题--注入类
- Android RecyclerView 打造带悬浮效果的联系人
- mysql如何进行以,分割的字符串的拆分
- 【Junit】Junit使用教程(二)
- c标签
- 从订单中心开始,聊聊「多KEY」类业务数据库水平切分架构实践
- 手游性能优化之深入理解Texture Compression
- 恶意代码分析实战 Lab 5-1 习题笔记