C ++:不允许浮点验证中的字母? [英] C++ : Do not allow letters in a float validation?

查看:59
本文介绍了C ++:不允许浮点验证中的字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个在其中进行验证的程序,程序会询问用户包装的重量,并适当地设置成本,如果用户输入一个减号,我会做到这一点给他们一个错误。


do {

clrscr();

cout<<" \ n输入包裹的重量交付;

cin>>重量;

if(weight< 0)

{

cout<<" \ n错误!只输入一个正数:;

}

if(weight< = 1)

{

cost = 2.50;

}

if(weight> 1&& weight< = 10)

{

cost = 7.50;

}

if(weight> = 10)

{

cost = 10.00 ;

}

} while(权重< 0);



但是如何阻止用户进入一封信应该只是数字吗?

谢谢你提前

解决方案

如果用户输入一个字母,cin.fail标志将会被提高。您将需要使用cin.clear清除它并以某种方式从流中删除有问题的字母或字母。做类似

展开 | 选择 | Wrap | 行号


我试过了,但你能告诉我如何把它放到我的代码中吗?


目前我已经包含了

#include< conio.h>

#include< iostream.h>


并且已经宣布



int numberQuotes,error;

char nextDay;

float 重量,成本,delieveryCharge,总计;


重量是我要验证的那个

到目前为止感谢它一直很有帮助!

要使用我发布的代码,您需要包含< string>。我不想要包含另一个头文件只是为了放入垃圾,但这是最简单的方法。


I have to create a program that has validation in it, The programme asks the user for the weight of a package, and sets the cost appropriately, I have a do in place do that if the user types in a minus number it gives them an error.

do{
clrscr();
cout<<"\n Enter the weight of the package to be delivered ";
cin>>weight;
if(weight<0)
{
cout<<"\n Error! ENTER A POSITIVE NUMBER ONLY";
}
if(weight<=1)
{
cost=2.50;
}
if (weight >1 && weight <=10)
{
cost=7.50;
}
if (weight>=10)
{
cost=10.00;
}
} while(weight<0);


But how to I stop the user entering a letter when it should be numbers only?
Thanks In Advance

解决方案

If the user enters a letter, the cin.fail flag will be raised. You will need to clear it with cin.clear and remove the offending letter or letters from the stream somehow. Do something like

Expand|Select|Wrap|Line Numbers


I tried this but can you tell me how to put it into my code?

Currently I have included
#include <conio.h>
#include <iostream.h>

and have declared


int numberQuotes,error;
char nextDay;
float weight,cost,delieveryCharge,total;

Weight is the one I want to validate

Thanks so far it has been helpful!


To use the code I posted, you need to include <string>. I don''t like having to include another header file just to put junk in, but it''s the easiest way to do it.


这篇关于C ++:不允许浮点验证中的字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆