+ 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.
8 Answers
+ 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.
+ 1
Vicent Roxan
i hope you have understand itāļø
+ 1
for multiwords string same thing is happening with the last word of multiword string.
an extra space is there.
+ 1
If you want you can try this code, this is my edition of this code.
https://code.sololearn.com/cjqz7KDVUFvJ
+ 1
Brian thank it worked !!
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
0
ok
0
but if i remove that space each words would stick together for example "the man" the output would be print out "hetayanmay"