Reputation: 187
I want to reverse a char string in c++. I wrote this 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; i < l-1; i++, j--){
word[j] = rev[i];
}
cout << rev << endl;
return 0;
}
In terminal it shows some characters like this:
83???uH??? ... Something like this
Upvotes: 0
Views: 5729
Reputation: 19
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char word[80] = "polymorphism";
char rev[80] = {'\0'};
int i = 0;
int last = strlen(word) - 1;
while(last >= 0) {
rev[i] = word[last];
i++;
last--;
}
cout << rev << endl;
return 0;
}
Upvotes: 0
Reputation: 4023
There are 3 changes I made to your code:
Change 1: Since string length is l
, indexing will be from 0
t ol-1
.
Change 2: rev
will be storing the values from word
, not the other way round.
Change 3: A proper string should be \0
terminated.
#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-1; i < l; i++, j--){ //change 1
rev[i] = word[j]; // change 2
}
rev[i]='\0'; // change 3
cout<<rev;
return 0;
}
Working ideone link: http://ideone.com/kIqeNF
Upvotes: 0
Reputation: 310980
Your character array rev is not zero terminated.
And istead of to write to rev you are writing to word.:)
word[j] = rev[i];
The loop is also wrong due to condition
i < l-1;
There must be
i < l;
The program can look the following way
#include <iostream>
#include <cstring>
int main()
{
char word[80] = "polymorphism";
char rev[80];
size_t n = std::strlen( word );
size_t i = 0;
for ( ; i < n; i++ ) rev[i] = word[n - i - 1];
rev[i] = '\0';
std::cout << word << std::endl;
std::cout << rev << std::endl;
return 0;
}
The program output is
polymorphism
msihpromylop
Take into account that you can do the same using standard algorithm std::reverse_copy
declared in header <algorithm>
.
For 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 is the same as above
polymorphism
msihpromylop
Upvotes: 3