String based question

I’m getting the correct output ,but an extra “-1” in the following question in SPOJ: http://www.spoj.com/problems/JNEXT/

Here’s my code:

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

int main()
{
int t;
char ss[10000];
string s;
cin>>t;
++t;
while(t--)
{
getline(cin,s);
s.erase(remove(s.begin(), s.end(),' '), s.end());
if(next_permutation(s.begin(),s.end()))
{cout<<s<<"

“;}
else
{cout<<”-1
";}
}
return 0;
}

OUTPUT:
2
-1  // unwanted
3 1 
-1
1 4 3
314

Pls help :slight_smile:

try capturing the newline char after T. Include a getline and in a dummy variable take input immediately after taking T.

Thxx a ton :))) , but may I know why that extra one comes?

P.S: Yea, that’s not the actual code for the question, I just tried a variant

The gist of matter is, there is a new line character after T , due to which obviously the next input goes into the new line. Your getline takes that input and thereafter goes to undefined behavior if s is used. You can google for the complete explanation.