+ 2

[SOLVED] Pig Latin challenges

#include <iostream> using namespace std; string w; int n; int main() { for(;cin>>w;){ n=w.length(); for(int i=0;i<n;i++){ swap(w[i],w[i+1]); cout << w[i] << w[n]; } cout << "ay "; } return 0; } Honestly I dont know why this code wont work thought the outputs is the same what it excepted.

14th Mar 2022, 2:43 PM
Vicent Roxan
Vicent Roxan - avatar
8 Respuestas
+ 5
Vicent Roxan a couple of problems are causing it to fail. 1) Inside the loop, the code is printing a null character after every letter in the word. Change: cout << w[i] << w[n]; To: cout << w[i]; 2) The loop is executing one too many times, causing the last character to get swapped with the terminating null. Change: n=w.length(); To: n=w.length()-1; --------- After these corrections, you will need to fix the output. In order to show the last character, change: cout << "ay "; To: cout << w[n] << "ay "; Better yet, remove the cout from inside the loop, and after the loop use: cout << w << "ay "; Now it will pass all tests.
15th Mar 2022, 5:13 AM
Brian
Brian - avatar
+ 1
Vicent Roxan i hope you have understand it✌️
14th Mar 2022, 3:04 PM
NonStop CODING
NonStop CODING - avatar
+ 1
for multiwords string same thing is happening with the last word of multiword string. an extra space is there.
14th Mar 2022, 3:06 PM
NonStop CODING
NonStop CODING - avatar
+ 1
If you want you can try this code, this is my edition of this code. https://code.sololearn.com/cjqz7KDVUFvJ
14th Mar 2022, 3:40 PM
SoloProg
SoloProg - avatar
+ 1
Brian thank it worked !!
15th Mar 2022, 12:12 PM
Vicent Roxan
Vicent Roxan - avatar
0
your code has a pixel of mistake. let me tell you why it is not working take a look at cout<<"ay " the reason your code is not working because at the end of the string there is an extra space that space is causing the error for example let input = "abcd" it piglating should be = "bcdaay" but you are getting piglating = "bcdaay " an extra space at the end of your piglatin string
14th Mar 2022, 2:59 PM
NonStop CODING
NonStop CODING - avatar
0
ok
14th Mar 2022, 3:00 PM
Vicent Roxan
Vicent Roxan - avatar
0
but if i remove that space each words would stick together for example "the man" the output would be print out "hetayanmay"
14th Mar 2022, 3:15 PM
Vicent Roxan
Vicent Roxan - avatar