My Pig Latin code doesn't work | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

My Pig Latin code doesn't work

I am sure that code run perfectly but when I put it in the playground question doesn't work, even when the answer is the same of the expected. My code is the following: #include <iostream> #include <sstream> using namespace std; int main() { string msg, word; string wd = ""; getline(cin, msg); stringstream ss(msg); while(ss>>word){ int len=word.length(); for(int i=1;i<=len;i++){ wd = wd + word[i]; } wd = wd + word[0] + "ay"; cout << wd << " "; wd = ""; } return 0; } Try it here: https://code.sololearn.com/c1d406dlgN1a/?ref=app

12th Sep 2021, 1:53 PM
CLAD
CLAD - avatar
4 Answers
+ 6
Strings are zero-indexed, the character at position word.length() is therefore not a valid character of the string; accessing it is undefined behaviour. Change the condition of your for loop to for ( ...; i < len; ... ) in order to fix the problem.
12th Sep 2021, 2:07 PM
Shadow
Shadow - avatar
+ 5
A͢J - S͟o͟l͟o͟H͟e͟l͟p͟e͟r͟ I don't think that is an issue, as all whitespace at the end of the string seems to be ignored anyway. I can print something like " \f \n \r \t \v " at the end and still pass the challenge.
12th Sep 2021, 2:19 PM
Shadow
Shadow - avatar
+ 3
Shadow I think that is working fine. He is getting expected result but I think adding extra space in result.
12th Sep 2021, 2:11 PM
A͢J
A͢J - avatar
+ 2
Shadow Yes got it. The problem was with index. That should be like: for (int i = 1; i < len; i++)
12th Sep 2021, 2:21 PM
A͢J
A͢J - avatar