for循环条件将无法正确检查

时间:2019-12-07 10:07:27

标签: c loops for-loop

我是C / C ++的初学者。我定义了一个反向strpbrk函数,该函数忽略了数学分析器项目的括号(称为strrpbrk_outside)。不幸的是程序忽略了条件ch != bound

任何人都可以解释真正的问题是什么吗?

char* strrpbrk_outside(char* current,char* target,char* bound,char opening,char closing){

    for(char* ch = current ; ch != bound ; --ch)
    {
        for(char* trg = target; *trg != '\0'; ++trg)
        {
            if ((*ch) == (*trg))
                return ch;
        }
        if ((*ch) == closing)
        {
            ch = find_opening(ch,bound,opening,closing);
            printf("current becomes %s\n",ch);
            if (ch == bound)
                printf("current == bound\n");
        }
    }
    for(char* trg = target; *trg != '\0'; ++trg)
    {
        if ((*bound) == (*trg))
            return bound;
    }
    return nullptr;
}

我已经测试了find_opening函数,没有任何问题。

char* find_opening(char* current,char* bound,char opening,char closing){
    int n = 0;
    int i = 0;
    if (*current == closing)
        --current;//Caution:
    for(; current != bound; --current)
    {
        if (*current == closing)
            n = n + 1;
        if (*current == opening)
        {
            i = i + 1;
            if (i > n)
                return current;
        }
    }
    if (*bound == opening)
    {
        i = i + 1;
        if (i > n)
            return current;
    }
    return nullptr;//Caution: returns current and also checks the bound character
};

这是我的测试代码:

#include <cstdio>
#include <string.h>
#include "AND_OR_NOT.h"

int main()
{
    char str[100] = "!<white1>|<white2>&(<sites>|<words>)";
    char str1[100] = "(!<white1>|<white2>)&(<sites>|<words>)";
    char* pch1 = str1 + 20;
    printf("%s\n",pch1-1);--pch1;
    char* prev = strrpbrk_outside(pch1,"&|",str1,'(',')');
    printf("%s\n",prev);

    char END;
    printf("press any key to end");
    scanf("%c",&END);
}

这是奇怪的结果:

)&(<sites>|<words>)
current becomes (!<white1>|<white2>)&(<sites>|<words>)
current == bound
current becomes (_,
current becomes²"
current becomes (1'w
current becomes (
current becomes (µ"
current becomes (1'w
current becomes (1'w
current becomes (1'w
press any key to end

cmd image

0 个答案:

没有答案