c++ 限制用户输入为正整数,或者是正的float数

118 阅读1分钟
#include <iostream>
#include <cstring>
#include <cstdlib> //stoi,stof
#include <algorithm>
#include <regex>

# if 0
int inputPositiveInt( )
{
    string s;
    int l;
    bool flag=false;

    for(;;)
    {
        if (flag==true)
            return stoi(s);
        cin>>s;
        l=s.length();
        char a[l];
        strcpy(a,s.c_str());
        for(int i=0;i<l;++i)
        {
            cout<<a[i]<<endl;
            if(!isdigit(a[i]))
            {
                cout<<"Please enter a positive integer!\n";
                s="";
                flag=false;
                break;
            }
            else
            {
                flag=true;
            }

        }

    }

}
#endif


int inputPositiveInt( )
{
    string s;
    regex int_regex("\\d+");
    do
    {
        cout<<"Input a positive integer: ";
        cin>>s;
    } while (!regex_match(s,int_regex));
    return stoi(s);

}

float inputPositiveFloat()
{
    string s;
    regex float_regex("\\d+\.?\\d+");
    do
    {
        cout<<"Input a positive number: ";
        cin>>s;
    }while(!regex_match(s,float_regex));

    return stof(s);

}

正则表达式:

  • \d:匹配一个数字
  • +:表示匹配前面的子表达式(即数字)一次或多次
  • .:匹配符号‘.’;
  • ?:匹配前面的子表达式零次或一次