Home > Back-end >  How to push string in a given range in stack in C ?
How to push string in a given range in stack in C ?

Time:11-05

int main()
{
    istringstream iss(dtr);
    Stack <string> mudassir;
    mudassir.push1(s1);
    string subs;
    do {
        iss >> subs;
        if (subs == "|post_exp|")
        {
            iss >> subs;
            while (subs != "|\\post_exp|")
            {
                mudassir.push(subs);
                cout << "heloo";
                iss >> subs;
            }
        }
    } while (iss);
}

I want to push a certain element of string in stack. But the problem is in this code, the inner while loop which has hello (just for testing) in it is running infinitely. I don't know why.

CodePudding user response:

the inner while loop which has hello (just for testing) in it is running infinitely. I don't know why.

Your inner while loop is not taking into account when the stream reaches the end of its data.

When operator>> reaches the end of the stream, it will put the stream into the eofbit state, and subs will be set to whatever data was left in the stream. Subsequent reads with operator>> will put the stream into the failbit state, and set subs to a blank value.

Your inner loop is ignoring the stream's state completely, and the blank value satisfies the != condition that you are checking. That is why your loop runs forever.

You need to pay attention to the stream's state. For example:

int main()
{
    istringstream iss(dtr);
    Stack <string> mudassir;
    mudassir.push1(s1);
    string subs;
    while (iss >> subs) {
        if (subs == "|post_exp|")
        {
            while (iss >> subs && subs != "|\\post_exp|")
            {
                mudassir.push(subs);
                cout << "heloo";
            }
        }
    }
}
  •  Tags:  
  • c
  • Related