繁体   English   中英

字符串校验形式 c++

[英]Checking form of a string c++

所以..我正在做一个程序,我要求用户输入一个字符串(这是一个多项式),我希望它具有以下结构:+/-(从 0 到 9 的数字)(x)(从0 到 9)。 括号中的内容可能会出现,也可能不会出现,所以基本上像“+2x-4x3”这样的东西会被接受,但“+2xx3--2x”不会,或者“+-x2”也不会。 我希望我的程序运行测试并检查输入数据是否具有这种结构。 因此,在将输入数据存储在一个名为“p”的字符串中之后,我使用以下循环来检查字符是 x、+、- 还是数字,但我找不到更精确的方法并检查其他可能的错误......有什么建议吗?

for (unsigned int i=0; i<p.length(); i++) {
    if ((p[i] < '0' ||  p[i] > '9') && p[i]!='+' && p[i] !='-' && p[i]!='x'  ) {

    std::cout << "Error.";
    return 1;
    }

您必须更仔细地定义表达式的语法(如所写,您的接受单+ )。

Exprs : Expr $ // End of input
      | Expr Exprs

Expr : sign [digits] x [digits] // I change you definition here as you accept sign only
     | sign digits

sign : + | -

digits : digit
        | digit digits

digit: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

然后,我们可以开始解析/词法分析功能

bool accept_sign(const char*& s) {
    if (*s != '-' && *s != '+') return false;
    ++s;
    return true;
}

bool accept_digits(const char*& s) {
    if (!std::isdigit(*s)) return false;
    while (std::isdigit(*s)) ++s;
    return true;
}

bool accept_x(const char*& s) {
    if (*s != 'x' /*&& *s != 'X'*/) return false;
    ++s;
    return true;
}

可能会更改Expr以允许简单的向前看:

Expr : sign x [digits]
     | sign digits x [digits]
     | sign digits
bool accept_Expr(const char*& s) {
    if (!accept_sign(s)) { return false; }
    if (accept_x(s)) { accept_digits(s); return true; }
    if (!accept_digits(s)) { return false; }
    if (accept_x(s)) { accept_digits(s); }
    return true;
}
bool accept_Exprs(const char*& s) {
    while (accept_Expr(s)) {/* empty */}
    return *s == '\0';
}

演示

或者,您可以将语法转换为正则表达式:

^([+-](\d*x\d*|\d+))+$ (或避免捕获组^(?:[+-](?:\d*x\d*|\d+))+$ )

const std::string tests[] = {"+3x", "+4x2-3", "+-2x", "+3xx"};
const std::regex regex(R"(^(?:[+-](?:\d*x\d*|\d+))+$)");

for (auto s : tests) {
    std::cout << s << (std::regex_match(s, regex) ? " is a valid polynomial\n"
                                                  : " is not a valid polynomial\n");
}

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM