You are close to the solution, but you have hit a behaviour that is not intuitive. Your problem is that when you cin
the number, the enter key that you press at the end is also taken by the following getline
, leading to an empty string. So getline
gives you a total of 3 strings, which clearly isn't what you want: you want to have 2, the first one being "Reverse this string" and the second one "OOP and DS", nothing more. What you did was working with 3, because there was a "ghost" one at the beginning. You used a "strange" exit condition for the loop over i
(normally i<number
is used, but you used i<=number
), which makes me think you must have noticed that with 2 iterations you were skipping "OOP and DS", and you tried to solve the problem, but you found a workaround instead of applying the correct solution.
As others have said, you can add cin.ignore(10000,'\n');
to solve the problem. This way, getline
will capture the right amount of lines (that is, 2). Then you have to restore the right exit condition, that is,
for(int i = 0; i < number; i++)
The other loop also looks suspicious:
for(int i = 0; i <= str.length(); i++)
Here you did the same thing (you used <=
instead of <
) but it turns out it's ok, because you are reading one character after the end of the string, which will give you the terminating character '\0' which you are checking for, so it's fine.
Apart from this I have just moved the cout << endl;
inside the for loop, after every reverted line has been printed. Oh, and I have changed the variable of the inner loop from i
to j
: it's better to avoid reusing the same names (i
is already used by the outer loop), because they can be confusing (though in this case they work well).
This is the final result (there are also a couple of cout
s that I added for debugging and that I left, though commented):
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
int number;
cin >> number; // number of strings to reverse
cin.ignore(10000,'\n');
for(int i = 0; i < number; i++)
{
string str;
getline(cin, str); // input
//cout << "Debug: i = " << i << ", string = " << str << endl;
std::stack<std::string> s; //stack
string str1 = "";
for(int j = 0; j <= str.length(); j++)
{
if(str[j] == ' ' || str[j] == '\0')
{ // add the word whenever it encounters a space
//cout << "Pushing '" << str1 << "'" << endl;
s.push(str1); //push the string
str1 = "";
}
else
str1 += str[j];
}
while(!s.empty())
{ // output
cout << s.top(); // simple displaying without space
cout << " ";
s.pop();
}
cout << endl;
}
}