c++ - 验证数字用户输入

标签 c++ validation

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

谁能给我一些指导?

此外,如果有人可以提供任何关于我如何做得更好的一般性提示,我将不胜感激。我正在学习 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);
}

最佳答案

您要做的是读取一行输入或一个字符串,然后尝试将该行转换为您的数字形式。 Boost 将其包装在 lexical_cast 中,但您根本不需要它。我已经回答了两次与您类似的问题,herehere .阅读这些帖子以了解发生了什么。

最终结果如下:

template <typename T>
T lexical_cast(const std::string& s)
{
    std::stringstream ss(s);

    T result;
    if ((ss >> result).fail() || !(ss >> std::ws).eof())
    {
        throw std::bad_cast();
    }

    return result;
}

按照我在这些帖子中概述的方式使用它:

int main(void)
{
    std::string s;
    std::cin >> s;

    try
    {
        int i = lexical_cast<int>(s);

        /* ... */
    }
    catch(...)
    {
        /* ... */
        // conversion failed
    }
}

这使用了异常。您可以通过捕获 bad_cast 异常来像上面的链接中概述的那样不抛出:

template <typename T>
bool lexical_cast(const std::string& s, T& t)
{
    try
    {
        t = lexical_cast<T>(s);

        return true;
    }
    catch (const std::bad_cast& e)
    {
        return false;
    }
}

int main(void)
{
    std::string s;
    std::cin >> s;

    int i;
    if (!lexical_cast(s, i))
    {
        std::cout << "Bad cast." << std::endl;
    }   
}

这有助于使 Boost 的 lexical_cast 不抛出异常,但如果您自己实现它,就没有理由浪费时间抛出和捕获异常。相互实现它们,其中抛出版本使用非抛出版本:

// doesn't throw, only returns true or false indicating success
template <typename T>
const bool lexical_cast(const std::string& s, T& result)
{
    std::stringstream ss(s);

    return (ss >> result).fail() || !(ss >> std::ws).eof();
}

// throws 
template <typename T>
T lexical_cast(const std::string& s)
{
    T result;
    if (!lexical_cast(s, result))
    {
        throw std::bad_cast("bad lexical cast");
    }

    return result;
}

您的代码中有更多麻烦:您全新一切!这是有原因的吗?考虑一下您的代码是否有任何部分抛出异常:现在您跳出了 main 并泄漏了所有内容。如果您堆栈分配您的变量,它们将保证销毁。

关于c++ - 验证数字用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2211656/

相关文章:

c++ - 使用 AVX 模拟 32 字节的移位

reactjs - React 如何制作一个具有固定值和动态值的输入字段

c++ - 外部 "C": What does and what doesn't need it?

c++ - 如何为 facebook 创建 oauth HMAC-SHA2 签名

c# - 为什么 C# PInvoke 不能与非托管 DirectX 一起工作

django - 检查所有 {% url %} 标签是否有错误

ios - 如何验证出生日期IOS7

c++ - 为什么从 `std::async` 阻塞返回的 future 的析构函数?

validation - 文本区域的 Dojo 验证

javascript - validate.unobtrusive.js,无法显示客户端验证消息,但它适用于表单验证