Help, random ascii char's appearing

I was trying to write a program that stores the message in a string backwards into a character array, and whenever I run it sometimes it successfully writes it backwards but other times it will add random characters to the end like this:

input: write this backwards
---
sdrawkcab siht etirwˇ
---
#include <iostream>
#include <string>
using namespace std;

int main()
{
string message;
getline(cin, message);
int howLong = message.length() - 1;
char reverse[howLong];
for(int spot = 0; howLong >= 0; howLong--)
{

reverse[spot] = message.at(howLong);
spot++;
}
cout << reverse;
return 0;
}






Using c style string isn't such a good idea. Its error prone.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{
string message;
getline(cin, message);
int howLong = message.length() - 1;
char reverse[howLong];
int spot;
for(spot = 0; howLong >= 0; howLong--)
{
reverse[spot] = message.at(howLong);
spot++;
}
reverse[spot] = 0;
cout << reverse;
return 0;
}
Instead of that you can do

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
string message;
getline(cin, message);
int howLong = message.length() - 1;
string reverse;
for(;howLong >= 0; howLong--)
{
reverse += message.at(howLong);
}
cout << reverse;
return 0;
}
That was how I wrote it the first time but this assignement required us to use a character array. Anywho, I fixed it by adding a null character to reverse[spot] just before I output reverse. Thanks for your help :)
Topic archived. No new replies allowed.