+ 1

Problems with Extra-Terrestrials

I have created a code in C++ like this: using namespace std; int main() { string s; cin >> s; for (int i = s.size(); i >= 0; i--) { cout << s[i]; } return 0; } When I check the result, the input was "garbage", and the expected output was "egabrag". My output was also the same. However, it said my output was incorrect. Does anyone know how to solve this? Thank you very much for your replies.

5th Sep 2021, 12:49 PM
adeadaccount
3 Réponses
+ 2
Word is garbage so loop should run 7 times That is from i=6 to i=0 but here loop is running 8 times from i=7 to i=0. At s[7] will fetch junk therefore compiler is warning you about it. It should be for( int i = s.size() - 1; i >= 0; i++)
5th Sep 2021, 1:10 PM
Morpheus
Morpheus - avatar
+ 1
Loop should be start from string size - 1 it will work fine
5th Sep 2021, 1:07 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 1
Thank you very much!
6th Sep 2021, 2:04 AM
adeadaccount