+ 1

When I try the "Extraterrestrial Code Coach," can anyone tell me why my code was invalid?

/*Input any word or even phrases then this code will flip it,like this: input=Reymark output=kramyeR */ #include <iostream> using namespace std; int main() { string word; getline(cin,word); int index,i; i = 0; index = word.size(); string reversed =""; while (index>=i){ reversed+=word[index]; index-=1; } cout<< reversed; return 0; }

16th Nov 2021, 7:29 AM
Reymark Marzan
Reymark Marzan - avatar
3 Antworten
+ 2
Reymark Marzan index=word.size() . Now index is one more than the last index of word. So when you access it will give some garbage value. So use index=word.size()-1 #include <iostream> using namespace std; int main() { string word; getline(cin,word); int index,i; i = 0; index = word.size()-1; string reversed =""; while (index>=i){ reversed+=word[index]; index-=1; reversed = string(reversed ); } cout<< reversed; return 0; }
16th Nov 2021, 11:49 AM
Arun Ruban SJ
Arun Ruban SJ - avatar
16th Nov 2021, 4:15 PM
Reymark Marzan
Reymark Marzan - avatar
+ 1
Reymark Marzan maybe because u are outputting char by char, instead try storing the result in a string first and then output. https://code.sololearn.com/c3r3FyUieMZ1/?ref=app
16th Nov 2021, 7:37 AM
ACE
ACE - avatar