如何在使用isalpha时产生异常

How to have an exception when using isalpha

本文关键字:异常 isalpha      更新时间:2023-10-16
{
  for(int i=0;i<strlen(argv[2]);i++)
  if(isalpha(argv[2][i]))
   {
    cout<<"X"<<endl;
    return (0);
   }
}

我不希望在输入指数函数(如1e10)时运行此命令知道的吗? ?

p。S试图区分数字和非数字,并希望1e10(和类似的)计数为数字

最简单的方法是使用c++内置的数字解析。将argv[2]放入istringstream中,然后尝试将其读取为double

#include <sstream>
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
   istreamstream buf(argv[2]);
   double x;
   if (buf >> x)
   {
       cout << "argv[2] is a number and it's value is " << x << "n";
   }
   else
   {
       cout << "argv[2] is not a numbern";
   }
}

希望对你有帮助。

编辑

由于以上不完全正确(即它是错误的),这里有另一个版本,希望更像OP所期望的。对于任何具有普通浮点数形式的字符串,函数is_a_number将返回true。"1e10"、"1.2"、"-3"、"1.2e-10"等

#include <iostream>
using namespace std;
static bool is_a_number(const char* str);
int main()
{
    if (is_a_number(argv[2]))
    {
        cout << "its a numbern";
    }
    else
    {
        cout << "not a numbern";
    }
}
static bool is_a_number(const char* str)
{
    bool mant_digits = false, exp_digits = true;
    if (*str == '-' || *str == '+')
        ++str;
    while (isdigit((unsigned char)*str))
    {
        mant_digits = true;
        ++str;
    }
    if (*str == '.')
    {
        ++str;
        while (isdigit((unsigned char)*str))
        {
            mant_digits = true;
            ++str;
        }
    }
    if (*str == 'e' || *str == 'E')
    {
        ++str;
        if (*str == '-' || *str == '+')
            ++str;
        exp_digits = false;
        while (isdigit((unsigned char)*str))
        {
            exp_digits = true;
            ++str;
        }
    }
    return *str == '' && mant_digits && exp_digits;
}

首先测试输入的格式是否正确,然后执行转换。如果输入无效,则抛出std::runtime_error异常。

class CommandLine
{
public:
    CommandLine(int argc, char*argv[]) : 
        locale(""), arguments(argv, argv+ argc)
    {
       if (argc < 3)
           throw std::runtime_error("not enough arguments.");
    }
    double GetValueXYZ()
    {
        if (!IsValidInput(arguments[2]))
            throw std::runtime_error(
                arguments[2] + " is invalid input for XYZ.");
        return std::strtod(arguments[2].c_str(), nullptr);
        // You could use a stringstream instead
    }
private:
    bool IsValidInput(const std::string& arg)
    {
        const auto& numpunct = std::use_facet<std::numpunct<char>>(locale);
        auto err = std::find_if(begin(arg), end(arg), [&](char c)
        {
            return !(std::isdigit(c, locale) || 
                c == numpunct.thousands_sep() ||
                c == numpunct.decimal_point());
        });
        return err == end(arg);
    }
    std::locale locale;
    std::vector<std::string> arguments;
};

int main()
{
    char*argv[] = { "main", "2.34" , "1.10"};
    try
    {
        CommandLine cmd(3, argv);
        std::cout << cmd.GetValueXYZ();
    }
    catch(std::runtime_error& e)
    {
        std::cout << e.what();
    }
}