如何在使用isalpha时产生异常
How to have an exception when using isalpha
{
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();
}
}
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 是什么导致了Unity 3D中的"错误线程异常"?
- 如何将strftime中的格式错误作为异常捕获
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 尝试使用智能指针时引发异常
- 函数如何通知用户它基于函数原型抛出异常?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- 如何在使用isalpha时产生异常