繁体   English   中英

C ++如何检查输入浮点变量是否有效

[英]C++ How to check an input float variable for valid input

我正在编写一个充当计算器的程序; 基于用户输入的字符,它执行特定操作。 该程序的结构似乎工作正常,但我希望能够检查错误的输入。 收到float变量后,有没有办法检查它是否包含除数字和小数以外的任何字符? 我尝试过isdigit ,这︰

if (!(cin >> x)) {
    cout << "You did not enter a correct number!" << endl; 
    return;
}

但似乎没有任何效果。

以下是我正在使用的一个简单操作函数的示例:

void Add(){
    float x = 0, y = 0, z = 0;
    cout << "Please enter two numbers you wish "
         << "to add separated by a white space:" << endl; 
    cin >> x >> y;
    z = x+y;
    cout << x << " + " << y << " = " << z << "." << endl;
    return;
}

您测试流的状态:

float x, y;
if (std::cin >> x >> y) {
    // input extraction succeeded
}
else {
    // input extraction failed
}

如果这对您不起作用,那么您需要发布不起作用的确切代码。

为了在期望数字的位置检测到错误的字符串输入,C ++不会自动知道您想要的是什么,因此一种解决方案是首先将输入作为字符串接受,验证这些字符串,然后验证(如果有效),然后使用atof()函数。

标准字符串类有一个名为find_first_not_of()的函数,可以帮助您告诉C ++您认为哪些字符有效。 如果函数找到不在列表中的字符,它将返回错误字符的位置,否则返回string :: npos。

// add.cpp

#include <iostream>
#include <string>
#include <cstdlib>    // for atof()

using namespace std;


void Add()
{
    cout << "Please enter two numbers you wish "
         << "to add, separated by a white space:"
         << endl;

    string num1, num2;

    cin >> num1;
    if( num1.find_first_not_of("1234567890.-") != string::npos )
    {
        cout << "invalid number: " << num1 << endl;
        return;
    }

    cin >> num2;
    if( num2.find_first_not_of("1234567890.-") != string::npos )
    {
        cout << "invalid number: " << num2 << endl;
        return;
    }

    float x = 0, y = 0, z = 0;
    x = atof( num1.c_str() );
    y = atof( num2.c_str() );
    z = x+y;

    cout << x << " + " << y << " = " << z << "." << endl;
}

int main(void)
{
    Add();
    return 0;
}

一种可能性是将输入作为字符串读取,然后使用boost lexical_cast转换为浮点。 如果整个输入转换为目标,则lexical_cast仅认为转换成功 - 否则,它将抛出bad_lexical_cast异常。

另一个想法是针对正则表达式测试输入。 浮点数的正则表达式示例可能是

-?[0-9]+([.][0-9]+)?

通过仅修改正则表达式,此方法还可以更轻松地改善匹配机制,并且可以针对不同类型的输入映射多个正则表达式,例如,可以将整数表示为

-?[0-9]+

等等。 但请记住,这仅测试输入是否为有效格式,之后仍然需要进行数值转换(我更喜欢boost :: lexical_cast)。

(您也可以通过http://gskinner.com/RegExr/尝试一下)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM