验证数字用户输入 [英] validating numerical user input

查看:151
本文介绍了验证数字用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个简单的CLI计算器工具作为练习。我需要确保n1和n2是数字的为了功能工作;因此,我想让程序在遇到预定的非数值时退出。

I am creating a simple CLI calculator tool as an exercise. I need to make sure n1 and n2 are numeric in order for the functions to work; consequently, I would like to make the program quit upon coming across a predetermined non-numeric value.

任何人都可以给我一些方向吗?

Can anyone give me some direction?

此外,如果任何人可以提供任何一般提示,可以做得更好,我会很感激。我正在学习c ++。

Additionally, if anyone can offer any general tips as to how I could have done this better, I would appreciate it. I'm just learning c++.

谢谢!

完整的代码如下。

#include <iostream>
#include <new>

using namespace std;

double factorial(double n) { return(n <= 1) ? 1 : n * factorial(n - 1); }

double add(double n1, double n2) { return(n1 + n2); }

double subtract(double n1, double n2) { return(n1 - n2); }

double multiply(double n1, double n2) { return(n1 * n2); }

double divide(double n1, double n2) { return(n1 / n2); }

int modulo(int n1, int n2) { return(n1 % n2); }

double power(double n1, double n2) {
    double n = n1;
    for(int i = 1 ; i < n2 ; i++) {
        n *= n1;
    }
    return(n);
}

void print_problem(double n1, double n2, char operatr) {
    cout<<n1<<flush;
    if(operatr != '!') {
        cout<<" "<<operatr<<" "<<n2<<flush;
    } else {
        cout<<operatr<<flush;
    }
    cout<<" = "<<flush;
}

int main(void) {

double* n1, * n2, * result = NULL;
char* operatr = NULL;

n1 = new (nothrow) double;
n2 = new (nothrow) double;
result = new (nothrow) double;
operatr = new (nothrow) char;

if(n1 == NULL || n2 == NULL || operatr == NULL || result == NULL) {
    cerr<<"\nMemory allocation failure.\n"<<endl;
} else {

    cout<<"\nTo use this calculator, type an expression\n\tex: 3*7 or 7! or \nThen press the return key.\nAvailable operations: (+, -, *, /, %, ^, !)\n"<<endl;

    do {    
        cout<<"calculator>> "<<flush;       
        cin>>*n1;

        cin>>*operatr;

        if(*operatr == '!') {
            print_problem(*n1, *n2, *operatr);
            cout<<factorial(*n1)<<endl;
        } else {

            cin>>*n2;

            switch(*operatr) {
                case '+':
                    print_problem(*n1, *n2, *operatr);
                    cout<<add(*n1, *n2)<<endl;
                    break;
                case '-':
                    print_problem(*n1, *n2, *operatr);
                    cout<<subtract(*n1, *n2)<<endl;
                    break;
                case '*':
                    print_problem(*n1, *n2, *operatr);
                    cout<<multiply(*n1, *n2)<<endl;
                    break;
                case '/':
                    if(*n2 > 0) {
                        print_problem(*n1, *n2, *operatr);
                        cout<<divide(*n1, *n2)<<endl;
                    } else {
                        print_problem(*n1, *n2, *operatr);
                        cout<<" cannot be computed."<<endl;
                    }
                    break;
                case '%':
                    if(*n1 >= 0 && *n2 >= 1) {
                        print_problem(*n1, *n2, *operatr);
                        cout<<modulo(*n1, *n2)<<endl;
                    } else {
                        print_problem(*n1, *n2, *operatr);
                        cout<<" cannot be computed."<<endl;
                    }
                    break;
                case '^':
                    print_problem(*n1, *n2, *operatr);
                    cout<<power(*n1, *n2)<<endl;
                    break;
                default:
                    cout<<"Invalid Operator"<<endl;
            }
        }
    } while(true);
    delete n1, n2, operatr, result;
}
return(0);
}


推荐答案

您自己的模板或强制自己使用异常与错误代码。 cin 单独处理您要求的一切。

No need for Boost or writing your own template or forcing yourself to use exceptions vs error codes. cin alone does everything you're asking for.

您可以测试 if ) if(!cin)来确定成功或失败。一个失败(例如,数字输入中的字母)将停止 cin 接受任何更多的输入。然后调用 cin.clear()清除错误并继续获取输入,从任何导致错误的文本开始。此外,您可以请求流对转换错误抛出异常: cin.exceptions(ios :: failbit)

You can test if ( cin ) or if ( ! cin ) to determine success or failure. One failure (eg, a letter in numeric input) will stop cin from accepting any more input. Then call cin.clear() to clear the error and resume getting input, starting with whatever text caused the error. Also, you can request that a stream throw exceptions on conversion errors: cin.exceptions( ios::failbit ).

所以,你可以这样做:

for (;;) try {
    double lhs, rhs;
    char oper;
    cin.exceptions( 0 ); // handle errors with "if ( ! cin )"
    cin >> lhs >> oper; // attempt to do "the normal thing"
    if ( ! cin ) { // something went wrong, cin is in error mode
        string command; // did user enter command instead of problem?
        cin.clear(); // tell cin it's again OK to return data,
        cin >> command; // get the command,
        if ( command == "quit" ) break; // handle it.
        else cin.setstate( ios::failbit ); // if command was invalid, 
                                           // tell cin to return to error mode
    }
    cin.exceptions( ios::failbit ); // now errors jump directly to "catch"
        // note that enabling exceptions works retroactively
        // if cin was in error mode, the above line jumps immediately to catch
    if ( oper != '!' ) cin >> rhs;
    // do stuff
} catch ( ios::failure & ) {
    cin.clear();
    cin.ignore( INT_MAX, '\n' ); // skip the rest of the line and continue
}

的iostreams的错误处理。您可以选择使用例外或手动测试,或两者兼用。

This is meant as a demonstration of error handling with iostreams. You can choose to use exceptions or manual testing or both.

这篇关于验证数字用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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