+ 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.
3 Antworten
+ 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++)
+ 1
Loop should be start from
string size - 1 it will work fine
+ 1
Thank you very much!