c++ - Reverse multi word string -


i want reverse string. when use simple cin strings reversed successfully. multi word string need cin.getline. problem upon using cin.getline first letter not displayed in reversed string. can please point me out mistake. in advance.

#include <iostream> using namespace std;   class rev_string{       char source[100], dest[100];      int pos_source, pos_dest;       public:          void func(){               pos_source=pos_dest=0;              cout<<"enter string reversed: ";              cin.getline(source,sizeof(source));              //cin>>source;              cout<<endl;                while(source[pos_source]!='\0')              pos_source++;                --pos_source;               while(pos_source!=0)              dest[pos_dest++]=source[pos_source--];                dest[pos_dest]='\0';                cout<<"the reversed string is: "<<dest<<endl;         }     };    int main(int argc, char** argv) {     rev_string ob;    ob.func();    return 0; }  

pos_source index of last character in array started 0. iterate through chars in array need track 0-index char, skipped now: after processing element index 1, source[pos_source--]; pos_source 0 , go out while loop. that's why loosing first character (which 0-index).

you can fix while(pos_source >= 0).

this typical "off-by-one" error.


Comments

Popular posts from this blog

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -