You are not logged in. Please login at www.codechef.com to post your questions!

×

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<<"\n";}
else 
{cout<<"-1\n";}
}
return 0;
}

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

Pls help :)

asked 14 Dec '17, 20:26

aetius_98's gravatar image

2★aetius_98
02
accept rate: 0%

edited 14 Dec '17, 20:28

vijju123's gravatar image

5★vijju123 ♦♦
15.4k12066

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

(14 Dec '17, 20:30) vijju123 ♦♦5★

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

(14 Dec '17, 20:35) aetius_982★

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.

(14 Dec '17, 23:08) vijju123 ♦♦5★
toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×644

question asked: 14 Dec '17, 20:26

question was seen: 157 times

last updated: 14 Dec '17, 23:08