给我一个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;
}

最佳答案

当你写

       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(),选择最佳选项;并且br.cptr已经是指针指向字符的类型,因此字符在字符串中的位置将被计算为&input[0],您需要减去指针本身,而不是地址。)

10-07 13:34
查看更多