0

Extra-terrestrials problem

Hi c++ developers, I'm solving Extra-terrestrials problem and I struggled with print the output with spaces in the for loop properly. Please explain to me how can I solve this(the problem is to print the input in the reverse order) #include <iostream> #include <cstring> using namespace std; int main() { char word[100]; cin.getline(word,100); for (int i=strlen(word); i>=0;i-- ){ cout<<word[i]; } return 0; }

3rd Mar 2021, 11:50 AM
Maryam Magdy
Maryam Magdy - avatar
5 Antworten
+ 3
Printing spaces is no issue, but you need to remember that arrays are null-indexed. This means you need to start iterating at strlen( word ) - 1 because otherwise you print the null character stored after the string as well, which messes up the comparison between your output and the solution.
3rd Mar 2021, 12:16 PM
Shadow
Shadow - avatar
+ 1
Usually the null character has no graphical represantation on a terminal at all, which is why it can be confusing if your output seemingly matches the solution, but does not appear to be correct.
3rd Mar 2021, 3:00 PM
Shadow
Shadow - avatar
0
Thank you for your reply. So, the null character is a space?
3rd Mar 2021, 2:55 PM
Maryam Magdy
Maryam Magdy - avatar
0
Yes that's what confused me, but I get it. An Invisible place :D
3rd Mar 2021, 3:02 PM
Maryam Magdy
Maryam Magdy - avatar
0
Yor comments were helpful Thx. And I just earned 10XP yay
3rd Mar 2021, 3:04 PM
Maryam Magdy
Maryam Magdy - avatar