这是用浮点值做输入验证的正确方法吗? [英] Is this the correct approach to do input validation with floating point values?

查看:134
本文介绍了这是用浮点值做输入验证的正确方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



函数检查一个字符串是否为一个字符串有效 double ...

  bool isDouble(double& amp ; destination,string& source)
{// 64位
bool goodValue = false;

if(!source.empty()){
errno = 0;
char * garbage = nullptr;
destination = strtod(source.c_str(),& garbage);

if(* garbage =='\0'&& errno!= ERANGE)
goodValue = true;
}

return goodValue;




$ b

检查字符串的有效32位<$ c

$ b $ is bong is long(long& amp; destination,string& amp; long& ;源)
{// 32位(基数10)
const短BASE = 10;
bool goodValue = false;

if(!source.empty()){
errno = 0;
char * garbage = nullptr;
destination = strtol(source.c_str(),& garbage,BASE);

if(* garbage =='\0'&& errno!= ERANGE)
goodValue = true;
}

return goodValue;




$ b

示例实现

  using namespace std; 

int main(){
字符串缓冲区;
double值;

cout<< 输入一个值:;
getline(cin,buffer,'\\\
');

if(isDouble(value,buffer))
cout<< 价值:<<值<< ENDL;
else
cout<< 错误:输入无效\;

返回0;





$ b

任何人都可以评论吗? >

解决方案

基于回答者和其他问题的一些例子,我回答了我自己的问题。根据FailedDev的建议,这个问题应该被标记为回答。所以这里是被接受的答案。 :)

After spending a good amount of time researching input validation, I combined a few ideas and came up with this:

Function to check a string for a valid double...

bool isDouble(double& destination, string& source)
{ // 64 bit
  bool goodValue = false;

  if (!source.empty()) {
    errno = 0;
    char *garbage = nullptr;
    destination = strtod(source.c_str(), &garbage);

    if (*garbage == '\0' && errno != ERANGE)
      goodValue = true;
  }

  return goodValue;
}

Function to check a string for a valid 32 bit integer...

bool isLong(long& destination, string& source)
{ // 32 bit (base 10)
  const short BASE = 10;
  bool goodValue = false;

  if (!source.empty()) {
    errno = 0;
    char* garbage = nullptr;
    destination = strtol(source.c_str(), &garbage, BASE);

    if (*garbage == '\0' && errno != ERANGE)
      goodValue = true;
  }

  return goodValue;
}

Sample Implementation

using namespace std;

int main() {
  string buffer;
  double value;

  cout << "Enter a value: ";
  getline(cin, buffer, '\n');

  if (isDouble(value, buffer))
    cout << "Value: " << value << endl;
  else
    cout << "ERROR: Invalid input\n";

  return 0;
}

Can anyone comment on if I am overlooking anything with this approach?

解决方案

Based on the feedback of those who answered and some of the examples in other questions, I answered my own question. As per FailedDev's suggestion, this question should be marked answered. So here is the accepted answer. :)

这篇关于这是用浮点值做输入验证的正确方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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