C++正在验证浮点值
C++ validating float
你好,我正在写我的作业,并且已经完成了,但有一件小事仍然让我感到困惑。我想验证float输入,所以如果用户键入char,它应该显示错误消息。我的挣扎是,无论我做什么,我的循环要么不起作用,要么永远循环。非常感谢你的建议。
float fuel;
char ch= ???;
if(fuel==ch)
{
do
{cout<<"Input is not valid. Please enter numeric type!";
cin>>fuel;}
while(fuel!=ch);
您尝试的方法是行不通的——因为您正在比较浮点值和字符,所以它们几乎永远不会相等。
试试这个方法:
bool notProper = true;
while(notProper) {
std::string input;
std::cin >> input
if( input.find_first_not_of("1234567890.-") != string::npos ) {
cout << "invalid number: " << input << endl;
} else {
float fuel = atof( num1.c_str() );
notProper = false;
}
};
尝试这样的代码。
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
bool CheckFloat( istream & is, float& n ) {
string line;
if ( ! getline( is, line ) ) {
return false;
}
char * ep;
n = strtol( line.c_str(), & ep, 10 );
return * ep == 0;
}
int main() {
float n;
while(1) {
cout << "enter an float: ";
if ( CheckFloat( cin, n ) ) {
cout << "is float" << endl;
}
else {
cout << "is not an float" << endl;
}
}
}
float num;
//Reading the value
cin >> num;
//Input validation
if(!cin || cin.fail())
{
cout << "Invalid";
}
else
{
cout << "valid";
}
您可以使用上述逻辑来验证输入!
作为我的源代码的一部分,请忽略"serror"的用法,它基本上只是抛出一个字符串错误:
//----------------------------------------------------------------------------------------------------
inline double str_to_double(const std::string& str){
char *end = NULL;
double val = strtod(str.c_str(), &end);
if(end == str.c_str() || end - str.c_str() != str.length())
serror::raise("string '%s' does not represent a valid floating point value", str.c_str());
if(val == +HUGE_VAL)
serror::raise("string '%s' represents floating point value which is too big", str.c_str());
if(val == -HUGE_VAL)
serror::raise("string '%s' represents floating point value which is too small", str.c_str());
return val;
}
相关文章:
- 正在尝试了解输入验证循环
- 如何在C++中检查2D数组中负值的输入验证
- LibGit2 SSH身份验证失败
- Vulkan验证层不断在VkQueuePresentKHR()上抛出图像布局错误
- constexpr上下文中std::initializer_list的验证
- 正在验证c++中用户的整数输入
- 加密++验证大文件签名
- C++卡验证问题
- 验证指针链
- 此代码验证公式是什么意思?
- cin 的十进制输入验证?
- 简单的 HTML 验证器
- 密码长度验证 (c++)
- 输入验证以筛选出字符、字符串和一系列整数
- 如何使用 CredUIPromptForWindowsCredentials验证凭据
- 指针验证的最佳实践?
- RSA_PKCS1签名验证
- 验证openssl c++中的签名,这是由JAVA DSA签名的?
- 使用 C++ 验证 NMEA 句子
- 为什么 WinInet 在通过 FQDN 连接时无法通过协商自动进行身份验证,但如果通过 IP 连接则成功?