Reverse order char array

I am having difficulty with a program that requires the user to input a series of chars, up to ten of them, in to an array and then the program outputs the array in reverse order. The problem is when I input less than ten chars I get a weird symbol in the spaces where there aren't any characters.

#include <iostream>
using namespace std;

void main()
{

char char_box[10];
cout << "Input a word" << endl;
cin >> char_box;

int i = 10;
while (i >= 0)
{
cout << char_box[i];
i--;
}
cout << endl;
system("pause");

}
http://i.imgur.com/qsWiR58.png
The problem is when I input less than ten chars I get a weird symbol in the spaces where there aren't any characters.

Those "weird" symbols are actually uninitialized variables. If you don't want to print these characters then maybe you want to limit your printout to the string length, not the size of the array.

http://pubs.opengroup.org/onlinepubs/009695399/functions/strlen.html
Unused elements of the character array do not contain spaces. You should find the terminating zero character and start outputing in the reverse order beginning with the element before the terminating zero character.
Last edited on
Could you replace char array with std::string? String has reverse iterators etc.
Thanks jlb, though I am getting an error when I type in
int i = strlen(word); I don't know why. Here is my code.

#include <iostream>
#include <string>
#include <string.h>
using namespace std;

void main()
{
string word;

cout << "Input a word" << endl;
cin >> word;

int i = strlen(word);
char char_box[i] = word;


while (i >= 0)
{
cout << char_box[i];
i--;
}
cout << endl;
system("pause");

}
Last edited on
You're getting an error because you are now using a std::string not a C-string. The strlen() function works only with a C-string. For a std::string you may want to first study up on the class: http://www.cplusplus.com/reference/string/string/ then use the function that returns the size of the string instead of strlen().

The following is also incorrect:
char char_box[i] = word;
char_box[i] is a single character word is a string. You can't assign a string to a single character.
Topic archived. No new replies allowed.