【问题标题】:C++ validating floatC++ 验证浮点数
【发布时间】:2013-03-11 13:14:18
【问题描述】:

你好,我正在写我的作业并且已经完成了,但是一件小事仍然让我感到困惑。我想验证浮点输入,所以如果用户键入 char 它应该显示错误消息。我的挣扎是,无论我做什么,我的循环要么不起作用,要么永远循环。非常感谢您的任何建议。

float fuel;
char ch= ???;

if(fuel==ch)
{
do
{cout<<"Input is not valid. Please enter numeric type!";
cin>>fuel;}

while(fuel!=ch);

【问题讨论】:

标签: c++ validation input


【解决方案1】:

您尝试这样做的方式行不通 - 因为您正在比较 float 和 char,所以它们绝对不会相等。

试试这个方法:

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;
  }
};

【讨论】:

  • 非常感谢您的快速回复。你能解释一下这行代码 if( input.find_first_not_of("1234567890.-") != string::npos )
  • 如果输入包含字符串中的字符以外的任何内容,它将返回该字符的位置,因此不返回 npos。
  • 这不会接受科学格式为 1e10,因此它的有效方式与 operator>> 的方式不同。
  • 不,它没有 - 但问题没有指定它也必须。如果需要,只需将“e”添加到字符串中。不完美,但也可以解析格式正确的科学数字。
  • 这会在像 32..32 或 2.4.4 这样的输入上失败
【解决方案2】:

试试这样的代码。

#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;
        }
    }
}

【讨论】:

    【解决方案3】:
    float num;
    
    //Reading the value
    cin >> num;
    
    //Input validation
    if(!cin || cin.fail())
    {
        cout << "Invalid";
    }
    else
    {
        cout << "valid";
    }
    

    您可以使用上述逻辑来验证输入!

    【讨论】:

    • 是的,但插播广告仍将包含未通过验证的号码。这意味着当您再次尝试时 - 您再次遇到相同的错误。如果在cplusplus.com上阅读this问题可以解决
    • @fredrik - 链接文章中的代码完全错误。更不用说它也不会删除未通过验证的文本。
    【解决方案4】:

    我的部分来源,请忽略'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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-21
      • 2015-07-14
      • 2012-12-14
      • 1970-01-01
      • 2020-03-16
      • 2015-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多