| New Reply |
Reverse words of a string C++ |
Share Thread |
| Dec20-11, 10:52 AM | #1 |
|
|
Reverse words of a string C++
Write a program to reverse words of a string individually, for example if you enter: I love C++, it should display I evol ++C
They've given the solution in my textbook but I don't quite understand the logic behind it. void main( ) { int l, i, k = 0 ; char str[80], word[80] ; cout<<"Enter any string"<<endl ; gets(str) ; strcat(str, " ") ; for(i = 0 ; str[i] !='0' ; i++) { if(str[i] != ' ') { word[k] = str[i] ; k = k + 1 ; } else { while(k > 0) { cout<<word[--k] ; } cout<<str[i] ; } } getch( ) ; } Could someone please explain what they have done here? |
| Dec20-11, 12:46 PM | #2 |
|
Mentor
|
When you post code, please surround your code with [code] and [/code] tags. This preserves indentation that might be there and makes your code easier to read.
|
| Dec20-11, 01:22 PM | #3 |
|
Mentor
|
You need to get a different book. Your's is fatally flawed.
I don't know if this code is in your text, for(i = 0 ; str[i] !='0' ; i++) If it is it means the sample code is untested (very very bad). That line should be for(i = 0 ; str[i] !='\0' ; i++) Using void main() is an unforgivable sin for a textbook on C++, as are using gets() and getch(). You need to get a better book. |
| Dec20-11, 01:29 PM | #4 |
|
|
Reverse words of a string C++
Also, C++ has built-in functions to do all this for you, e.g.
http://www.cplusplus.com/reference/algorithm/reverse/ |
| Dec20-11, 01:33 PM | #5 |
|
|
Yeah, it is for(i=0 ; str[i] != '/0' ; i++)
Sorry that was a typo on my part. I do, however, agree that it is an extremely bad book. I use other books for concepts but I can't really help it when it comes to writing programs cause this book is provided by my education system. |
| Dec20-11, 01:39 PM | #6 |
|
|
I know using gets( ) causes the program to crash since it does not let you specify a limit on how many characters are to be read
But why is using getch( ) bad? |
| Dec20-11, 01:47 PM | #7 |
|
Mentor
|
Besides, it's best if beginners at first avoid huge parts of the huge C++ library. Students need to learn how to iterate, how to search, how to write simple algorithms. Once they have learned such techniques they can be told "Oh, by the way. Almost all the stuff you've learned to write the last few weeks is already written for you in the C++ library." |
| New Reply |
Similar discussions for: Reverse words of a string C++
|
||||
| Thread | Forum | Replies | ||
| The 1st 3 words... | Fun, Photos & Games | 27 | ||
| "to the nearest order of magnitude." | General Physics | 6 | ||
| how many words... | Set Theory, Logic, Probability, Statistics | 5 | ||
| How many words | General Discussion | 27 | ||
| Words | Forum Feedback & Announcements | 3 | ||