Error finding

i had to do a simple program that takes the user char input and makes it backwords. i basically have it but it prints out these other charatures before it.

heres the code

#include<iostream>
#include<conio.h>
#include<windows.h>
using namespace std;

int main ()
{
char word [20];
cout<<"Enter a word and I will print it out backwards :D"<<endl;
cin>>word;

for(int i=20;i>=0;i--)
{
cout<<word[i];
}
_getch();
return 0;

}
It displays the extra characters because the array size is 20. so apart from the user input it will pad with some characters in the front.

Try this...use string

#include<iostream>
#include<string>
#include<conio.h>
#include<windows.h>

using namespace std;

int main ()
{
string word;
cout<<"Enter a word and I will print it out backwards :D"<<endl;
getline(cin, word);

for(int i=word.size()-1;i>=0;i--)
{
cout<<word[i];
}

_getch();
return 0;
}
You didn't consider that your word might not use the full array.
Include <string.h> and change your loop for
1
2
3
4
for( int i = strlen(word)-1; i>= 0; i++ )
{
    cout << word[i];
}
Topic archived. No new replies allowed.