- 5

why doesn't my code accept

Pig latin

3rd Jan 2022, 7:11 AM
Alexey
Alexey - avatar
9 Answers
+ 3
Alexey Your code is unnecessary long, but don't mind if u are a beginner . Now come to the issue with your code:_______ Basically,while shifting characters to the left---loop running to the end character of the string and you are aceessing the character of string(pigl[x]) out of bounce[y+1] when y = a. Most Sad thing here is that the subscript operator [ ] does no bounce checking , that's why you are not being notified what is going wrong with your code. Use .at() method instead of [ ] , you will get an exception thrown `out of range`. Because .at() method does bounce checking. Also pigl[x][0]=' '; doesn't make any sense as you are shifting left each character instead make pigl[x][a-1]=' '; that is the last character must be space. Correct version is attached......... https://code.sololearn.com/ccwcbnxyfVp3/?ref=app
3rd Jan 2022, 8:16 AM
saurabh
saurabh - avatar
+ 3
ROOKIE very good work in discovering the array bounds violation! Alexey keep striving to write cleaner code. With a better understanding of strings the code can be reduced to a few lines with no worries about array boundaries: #include <iostream> using namespace std; int main() { string word; while (cin >> word) cout<<word.substr(1)<<word[0]<<"ay "; return 0; }
3rd Jan 2022, 1:21 PM
Brian
Brian - avatar
+ 1
#include <iostream> #include <vector> using namespace std; int main() { string num; vector<string> pigl; while (std::cin>>num){ pigl.push_back(num); } int h = pigl.size(); string fbuk[h]; string piglang; for(int x=0; x<h; x++){ fbuk[x]=pigl[x][0]; fbuk[x]+="ay"; pigl[x]+=fbuk [x]; pigl[x][0]=' '; int a = pigl[x].length(); for (int y = 0; y<a; y++){ pigl[x][y]=pigl[x][y+1]; } //cout << pigl [x] <<" "; piglang+=(pigl[x]+" "); } cout << piglang; return 0; }
3rd Jan 2022, 7:15 AM
Alexey
Alexey - avatar
+ 1
Alexey Follow comments in my code to see the changes required
3rd Jan 2022, 8:19 AM
saurabh
saurabh - avatar
0
Why doesn't my code accept. It seems to be working, but they ask to fix it. Perhaps the problem is in the number of characters in the string in the output.
3rd Jan 2022, 7:14 AM
Alexey
Alexey - avatar
0
Thank you. I'm just learning
3rd Jan 2022, 7:30 AM
Alexey
Alexey - avatar
0
Thanks a lot for the help, and thanks for the detailed description. I used only those functions that I knew and that I found on the Internet, that's why the code is so long)). How would you solve this problem?
3rd Jan 2022, 9:35 AM
Alexey
Alexey - avatar
0
Brian This is genius. Much easier than mine.
3rd Jan 2022, 4:22 PM
Alexey
Alexey - avatar