Reputation: 57312
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;
}
Upvotes: 1
Views: 382
Reputation: 393
Use a proper C++ solution.
Inline reverse the message:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string message;
getline(cin, message);
//inline reverse the message
reverse(message.begin(),message.end());
//print the reversed message:
cout << message << endl;
return 0;
}
Reverse a copy of the message string:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string message, reversed_message;
getline(cin, message);
//reverse message
reversed_message = message;
reverse(reversed_message.begin(), reversed_message.end());
//print the reversed message:
cout << reversed_message << endl;
return 0;
}
If you really need to save the reversed string in a C string, you can do it:
char *msg = (char *)message.c_str();
but, as a rule of thumb use C++ STL strings if you can.
Upvotes: 1
Reputation: 308111
Instead of reversing into a character buffer, you should build a new string. It's easier and less prone to bugs.
string reverse;
for(howlong; howLong >= 0; howLong--)
{
reverse.push_back(message.at(howLong));
}
Upvotes: 1
Reputation: 8143
Since you can't declare an array with a length that is only known at runtime, you have to use a container instead.
std::vector<char> reverse(message.length());
Or better, use std::string
. The STL also offers some nice functions to you, for example building the reversed string in the constructor call:
std::string reverse(message.rbegin(), message.rend();
Upvotes: 2
Reputation: 41232
The buffer reverse
needs to be message.length() + 1
in length so that it can store a null termination byte. (And the null termination byte needs to be placed in the last position in that buffer.)
Upvotes: 4