Extra-Terrestrials task issue | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Extra-Terrestrials task issue

Why my code don't pass the test , i think its because of 'space' somewhere in the output. So how can i fix it? // #include <iostream> #include <cstring> using namespace std; int main() { char string[32]; cin>>string; for(int i = strlen(string); i >= 0;i--) { cout<<string[i]; } }

21st Apr 2020, 2:37 PM
Eskalate
Eskalate - avatar
6 Answers
+ 4
Let me answer your question with another question. Lets say we have the string "hello". strlen will return 5. Is string[5] a valid index?
21st Apr 2020, 2:52 PM
Dennis
Dennis - avatar
+ 1
So what do you think the problem is?
21st Apr 2020, 2:54 PM
Dennis
Dennis - avatar
+ 1
While a string is indeed the better option, it would still give you the same problem. Why don't you try your 2nd solution, it looks very promising. :)
21st Apr 2020, 2:59 PM
Dennis
Dennis - avatar
+ 1
A string like "hello" isn't actually stored like that in memory. It's actually stored as "hello\0" where '\0' is the null character, an unprintable character that marks the end of the string. (it may appear as a space, but it's not a space) By (effectively) doing string[5] you would therefore print the null character which should not be part of the output. "\0olleh" != "olleh"
21st Apr 2020, 3:02 PM
Dennis
Dennis - avatar
0
Valid index will be 4
21st Apr 2020, 2:53 PM
Eskalate
Eskalate - avatar
0
Maybe i should use string str , not the char str. Or make in cycle int i = strlen(string)-1
21st Apr 2020, 2:57 PM
Eskalate
Eskalate - avatar