-1

I have been trying to solve a problem which require unknown number of string inputs. Below is my code which is not working as required. I just need help in how to take input of multiple lines.

#include<bits/stdc++.h>
using namespace std;
void solve(string s)
{
    // cout << "String is : " << s << endl;
    stack<char> stk;
    for(int i = 0; s[i] != '\0'; i++)
    {
        if(s[i] == '[')
            stk.push(s[i]);
        else if(s[i] == ' ')
        {
            if(stk.top() == s[i])
                stk.pop();
            else
                stk.push(s[i]);
        }
        else if(s[i] == ']')
        {
            if(stk.top() == ' ')
                stk.pop();
            if(stk.top() == '[')
                stk.pop();
        }
    }
    cout << (stk.empty()? "YES" : "NO");
    // while(!stk.empty())
    // {
    //     cout << stk.top();
    //     stk.pop();
    // }
    // cout << '\n';
}
int main()
{
    string s;
    while(getline(cin, s))
    {
        solve(s);
    }
}

Input is given below.

    Input is :
    [] [ [ ] ]
    [ []]
    [] ]
    ][


But I am not able to read multiple lines. As In my code there is a commented line (at the beginning of solve function)
cout << "String is : " << s << endl; . This line not giving output for any string input (Don't worry I know I have to decomment it). What is the mistake in taking input for the strings?
Thank You..

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
dukeforever
  • 298
  • 1
  • 7
  • 1
    **Related:** [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – Rohan Bari Jul 24 '20 at 06:51

1 Answers1

0

Your multiline input thing is working just fine : Sample Run.

You aren't getting any output probably because of segmentation fault : Sample Run.

To fix it, just change all your conditions calling stk.top() like : if(stk.top() == ' '), with something like: if(not stk.empty() and stk.top() == ' '), i.e. first check if the stack is not empty then call stk.top() : Sample Run.

brc-dd
  • 10,788
  • 3
  • 47
  • 67