how to reverse words in a sentence without helper methods in c++?

c++, reversing, string

Solution

Your intuition is right: the loop isn't being executed. The problem is in the line:

for(int i = 0; i > indexes[0]; i++)

The comparison should be `i < indexes[0]`.

Problem

I need to read string of characters (with spaces) and reverse it. First i read a string of characters from console. ``` char array[100]; for(int i = 0; i < sizeof(array); i++) array[i] = '0'; for(int i = 0; i < sizeof(array); i++) cout<<array[i]<<" "; cout<<"\n\nenter your string: "; cin.getline(array, 100); cout<<"\n"; for(int i = 0; i < sizeof(array); i++) cout<<array[i]<<" "; ``` Then i create and fill indexes array. (to remember space spots) ``` cout<<"\n\nindexes: "; int indexes[20]; for(int i = 0; i < 20; i++) { indexes[i] = 0; } // filling the indexes array int j = 0; for(int i = 0; i < sizeof(array); i++) { if(array[i] == '0') break; if(array[i] == ' ') indexes[j++] = i; } // validating indexes array for(int i = 0; i < sizeof(indexes); i++) { //if(indexes[i] == 0) break; cout<<indexes[i]<<" "; } ``` Here is the begining of my (i guess not smart) algorythm. I want to reverse first word. Seems like this chunk never executes. Why? ``` // first word int j1 = indexes[0]-1; for(int i = 0; i > indexes[0]; i++) { new_array[i] = array[j1-i]; cout<<"\naction\n"; } ``` Print new_array to console: ``` for(int x = 0; x < sizeof(new_array); x++) { if(new_array[x] == '0') break; cout<<new_array[x]<<" "; } ``` The result is: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 enter your string: this is my string t h i s i s m y s t r i n g 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 indexes: 4 7 10 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -858993460 -858993460 100 -85 8993460 -858993460 100 -858993460 -858993460 100 -858993460 -858993460 193628786 0 544434464 1931508077 1852404340 805314663 808464432 808464432 808464432 808464 432 808464432 808464432 808464432 808464432 808464432 808464432 808464432 808464 432 808464432 808464432 808464432 808464432 808464432 808464432 808464432 808464 432 -858993460 -742139265 6421640 18244041 1 9932784 9928256 -742139185 0 0 2129 674240 -1920 570026249 0 6422528 0 6421580 0 6421712 18223374 -759898201 0 64216 48 18244541 new array: Why the indexes array contains these numbers after zeros? It's length is only 20. And why the new_array is not printed? I know that my solution is very very cumbersome)

Original source

Related problems