使用指针查找不平衡括号之间的字符位置

时间:2018-02-19 12:35:03

标签: c++ pointers parentheses

我遇到了一个C ++编程问题:在一个字符串中我需要找到更好或没有平衡的括号。如果没有,使用指针我应该找到未闭合括号之间的字符位置(在第二个开口和最近的闭合之间)。 我知道问题陈述有点令人困惑。我认为它应该以某种方式工作:

输入#1:

((aba)aaab)

输出:

OK.

输入#2:

(aa(a)ab

输出:

Parentheses not balanced: between characters 1 and 6.

下面的代码通过封闭的括号检查解决了部分问题,并且还有一个结构来保留开放式数据的地址。我不确定如何将指针用于此目的,有些尝试没有给出任何结果,所以我需要一些帮助。

#include<iostream>
#include<string>
#include<stack>

using namespace std;

struct br_data{
    char br_t;
    char *cptr;     //store the address of the opening parenthesis
};

int main (){
    string input;
    int addr;
    br_data br;
    getline(cin, input);

    stack<br_data> braces;
    char *a = input[0];  
    auto init_char = static_cast<void*>(&a); //store the address of the first character in the input string
    cout << static_cast<void*>(&a) << endl;  //gives the address in memory
    for(auto c: input) {
        if (c == '(') {
            br.br_t = c;
            br.cptr = &c;   //storing the address of the first parenhesis
            braces.push(br);
        } else if (c == ')' ) {
            if (braces.empty())
                cout << "This line does not contain unclosed parentheses\n";
            if (!braces.empty())
                braces.pop();
        }
    }
    if (!braces.empty()){
        //int addr = br.cptr;
        cout << "This line does not contain unclosed parentheses\n";
        //int pos = (&br.cptr) - (&a); //how to calculate the position??
        cout << "Position of the second opening parenthis is " << () << endl;
        //cout << "Position of the nearest closing parenthis is " << -how?? (static_cast<void*>(&br.cptr)) << endl;
    }
    if (braces.empty()){
        cout << "Parentheses are balanced in this line\n";
    }

    return 0;
}

1 个答案:

答案 0 :(得分:2)

写作时

       br.cptr = &c;   //storing the address of the first parenhesis

您实际上存储了之前声明的char类型的本地对象的地址:

auto c: input

当你退出循环时,它正式悬空。

一个最简单的解决方案是实际考虑字符串的字符,而不是它们的本地副本:

for(auto &c: input) {

(并且,更好的是,将auto更改为char以更清晰,保持源长度相同)。然后,您可以继续查看您的解决方案是如何进一步修复的。

(一些额外的免费建议:input [0]是char类型的右值引用,因此将它分配给char *类型的变量是没有意义的,你在该行中尝试做的是实际上写为char *a = input.c_str();input.data()或甚至&input[0],选择最佳选项; br.cptr已经是指向char的类型,因此角色的位置在一个字符串将被计算为br.cptr - a,你需要减去指针本身,而不是它们的地址。)

相关问题