char - Reversing a word : C++ -


i want reverse char string in c++. wrote code:

#include <iostream> #include <string.h>  using namespace std;  int main(){     char word[80] = "polymorphism";     char rev[80];     int i, j;     int l;     l = strlen(word);     for(i = 0, j = l; < l-1; i++, j--){         word[j] = rev[i];     }     cout << rev << endl;     return 0; } 

in terminal shows characters this:

83???uh??? ... 

your character array rev not 0 terminated.

and istead of write rev writing word.:)

    word[j] = rev[i]; 

the loop wrong due condition

i < l-1; 

there must be

i < l; 

the program can following way

#include <iostream> #include <cstring>  int main() {     char word[80] = "polymorphism";     char rev[80];      size_t n = std::strlen( word );      size_t = 0;     ( ; < n; i++ ) rev[i] = word[n - - 1];     rev[i] = '\0';      std::cout << word << std::endl;     std::cout << rev << std::endl;      return 0; } 

the program output is

polymorphism msihpromylop 

take account can same using standard algorithm std::reverse_copy declared in header <algorithm>. example

#include <iostream> #include <cstring> #include <algorithm>  int main() {     char word[80] = "polymorphism";     char rev[80];      size_t n = std::strlen( word );      *std::reverse_copy( word, word + n, rev ) = '\0';      std::cout << word << std::endl;     std::cout << rev << std::endl;      return 0; } 

the program output same above

polymorphism msihpromylop 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -