+ 1

What's going wrong? C++

My code for pig latin challenge doesn't work very well, can you help me guys? https://code.sololearn.com/c0uKGLTGv8Ju/?ref=app

10th Jan 2020, 4:57 PM
Gabriel Martins
Gabriel Martins - avatar
5 Respostas
+ 3
Okay, found the second problem, sorry for the delay. Anyway, the issue seems to be that you are printing characters over the bounds of the actual string. You can verify this by replacing all uses of [] by calls to the at() method (another std::string method), it will throw an error. This happens because you need less iterations than you have characters in the string, since you essentially print multiple letters when encountering a space. To solve this, you should not compare 'i' to "length - 1", but "letter" instead. Also, you need to print that last chatacter too, and once everything is printed, terminate the loop via "break", to make sure the loop stops once the last character has been encountered. So modify the second if-statement to something like: if ( letter == length - 1 ) { cout << word[ letter ] << word[ firstLetter ] << "ay"; break; } That should about do the job.
10th Jan 2020, 6:11 PM
Shadow
Shadow - avatar
+ 4
I don't fully understand the sizeof( word ) / 2 use. First of all, sizeof() will not give you the exact number of characters stored inside your string, because an instance of std::string also has an additional field to keep track of its size, so the object will be larger than the actual string. Use either the size() or the length() member function for this, they're equal and will give an accurate result. Also, why devide by 2?
10th Jan 2020, 5:14 PM
Shadow
Shadow - avatar
+ 2
~ swim ~ Same first impression. XD
10th Jan 2020, 5:18 PM
Shadow
Shadow - avatar
+ 1
Thanks for show other alternatives XD
10th Jan 2020, 5:22 PM
Gabriel Martins
Gabriel Martins - avatar
0
Shadow, I divided by 2 because, when I called cout << sizeof(), the values were equal double of the number of characters, I'm a beginner and didn't know this other commands...
10th Jan 2020, 5:20 PM
Gabriel Martins
Gabriel Martins - avatar