1

I want to display a sentence in reverse order. For eg "I have money" to "money have I". I have used stack like this but I don't understand why I can't push elements into my stack (stack size always = 0 when I check at the end)

#include<bits/stdc++.h>
using namespace std;

int main() {
    string s;
    cin >> s;
    string temp;
    stack<string> stk;
    for (int i = 0; i < s.size(); i++) {
        if (s[i] != ' ') {
           temp.push_back(s[i]);
           cout << temp << endl;
        } else {
            stk.push(temp);
            temp = "";
        }
    }
    for (int i = 0; i < stk.size(); i++) {
        cout << stk.top() << endl;
        stk.pop();
    }
    cout << stk.size();
}
  • There's several things here that should be addressed, but for a start: when you do "stk.pop()" you automatically remove the top element from the stack. The for-loop at the end of your code will iterate through the stack, print out all elements and empty the stack. This is why the size is always 0, after the loop. – waykiki Nov 27 '21 at 14:17
  • 1
    That first `for` loop could be removed and simply this: `std::istringstream strm(s); while (strm >> temp) stk.push_back(temp);` No need to check for spaces or other logic, such as setting `temp` to an empty string. – PaulMcKenzie Nov 27 '21 at 14:24
  • 1
    @Ballantines No, the input is buggy. `std::cin >> s;` will stop reading at the first white space. The last loop is also buggy. Every iteration will _increase_ `i`, but also _decrease_ `stk.size()`, so you only handle half the elements. – Lukas-T Nov 27 '21 at 14:27
  • 1
    You should be using `std::getline` to read the string in, not `cin`. You should print out the value you read in, and you will see it doesn't contain any words after the first space. – PaulMcKenzie Nov 27 '21 at 14:27
  • @PaulMcKenzie One could also combine both your suggestions and use `while (std::cin >> s)`, I think. – Lukas-T Nov 27 '21 at 14:28
  • 2
    [Why should I not `#include `?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) [Why is `using namespace std;` considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Evg Nov 27 '21 at 14:35
  • Thanks for all your comment, I have figured out my mistake – Ballantines Nov 27 '21 at 16:06

3 Answers3

2

Here is a complete answer. It is very short and concise.

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

int main() 
{
    std::string temp;
    std::stack<std::string> stk;
    while (std::cin >> temp)
        stk.push(temp);

    while (!stk.empty())
    {
      std::cout << stk.top() << " ";
      stk.pop();
    }
}  

Note that there are no loops to check for spaces.

Second, the while loop is much more intuitive and easier to write than your for loop, which is buggy. In your for loop, you have a shrinking stack and an increasing i index going on at the same time, which is wrong.

The proper way to print out a stacks entries while emptying the stack is to use a while (not empty) paradigm, while inside the loop, popping the top element.

Last, and not least, the code doesn't have all of the flaws such as including the bits header, and using namespace std;

Live Example

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
0

As a variant you can consider this solution of your problem.

#include <iostream>
#include <vector>
#include <string>
using namespace std;
const int maximumSize=10;
vector<int> visited(maximumSize, 0);
vector<string> sentence={"I", "have", "money"};
vector<string> reverseSentence;
void showContentVector(vector<string> input)
{
    for(int i=0; i<input.size(); ++i)
    {
        cout<<input[i]<<" ";
    }
    return;
}
void dfs(int current, int previous)
{
    if(visited[current]==1)
    {
        return;
    }
    visited[current]=1;
    for(int next=(current+1); next<sentence.size(); ++next)
    {
        if(next==previous)
        {
            continue;
        }
        dfs(next, current);
    }
    reverseSentence.push_back(sentence[current]);
    if(current==0)
    {
        showContentVector(reverseSentence);
    }
    return;
}
int main()
{
    dfs(0, -1);
    return 0;
}

Input:

I have money

Here is the result:

money have I
Vadim Chernetsov
  • 370
  • 1
  • 2
  • 14
  • This is overkill. You don't need to do depth-first-search to accomplish such a simple task. – PaulMcKenzie Nov 27 '21 at 14:32
  • @PaulMcKenzie, Respected Mr. McKenzie, You are right without any doubts. This method is considered as a variant of the solution and it works. – Vadim Chernetsov Nov 27 '21 at 14:36
  • Since I do not think any longer that this is reality, answering any question with a DFS answer (please check out user "Vadim Chernetsov"), my guess is that this is a test by stackoverflow, how friendly we are, even looking at, let's say, inapropriate answers. I will one time flag it to check . . . – A M Nov 27 '21 at 16:43
0
#include <bits/stdc++.h>
using namespace std;

vector <string> splitstringarray;
void splitstring(string s)
{
    stringstream ss(s);
    string word;
    while (ss >> word) {
        splitstringarray.push_back(word);
        cout << word << endl;
    }
}

int main()
{
    splitstring("you sample string")
    for (int i = splitstringarray.size(); i > 0; i--)
    {
        cout << splitstringarray[i];
    }
    return 0;
}
  • 1
    [Why should I not `#include `?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) [Why is `using namespace std;` considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Evg Nov 27 '21 at 14:35
  • Using global namespace can lead to name collisions. Mostly used #include, as that is mentioned in the question so I have not changed. – Gautam Jangid Dec 04 '21 at 16:06