I'm actually working on a C++ Invert String/Char[] Methods
#include <iostream>
using namespace std;
void inverse(string input)
{
int length = input.length();
char* output = new char[length];
for(int i = 0; i < length; i++)
{
output[length - (i + 1)] = input[i];
}
cout << output << endl;
delete output;
}
int main(int argc, char *argv[])
{
while(true)
{
string in;
cin >> in;
inverse(in);
}
return 0;
}
The problem is, when i enter a string with 3/5/7 and so on letters, then it will invert, then if its correct, but if i enter a string length of 2/4/6 and so on characters there inverted string has random chars on his and and only when i enter these length of number.
I'm so confused because this error only appears with even numbers.
Here's a little example: Here's a little example:
Here is the new code (everything works fine here), i know it has something to do with the /0 on the end of the array but why only the even numbers.
#include <iostream>
using namespace std;
void inverse(string input)
{
int length = input.length();
char* output = new char[length + 1];
for(int i = 0; i < length; i++)
{
output[length - (i + 1)] = input[i];
}
output[length] = '\0';
cout << output << endl;
delete output;
}
int main(int argc, char *argv[])
{
while(true)
{
string in;
cin >> in;
inverse(in);
}
return 0;
}
Can anybody help me find a solution for this?
Your string is not null-terminated. Try
void inverse(string input)
{
reverse( input.begin(), input.end() );
cout << input << endl;
}
For this to work, you need to include the algorithm header which defines the std::reverse() function.
The reason it does not work for even numbers could be the fact, that memory allocations usually reserve a little more memory, so that memory boundaries are properly aligned. Therefore, rounding up to even numbers is not a waste. That's just a guess. However, I would strongly recommend you avoid undefined behavior.
You got garbage at the end of your string because it wasn't ended with \0. Printing such strings is an undefined behavior in c++.
You were just lucky that your code worked for even lengths. On my machine, for example, it works good for lengths of 1,2,3,5,6,7 and 8 and prints garbage for 4.
UP: Actually, try to avoid the UB: the c++ standard does not specify what happens when you have the UB - theoretically, you program may crash, or your computer may blow up, or a demon may appear from your nose. In this particular case I would recommend using std::string as a container for output if you, for some reason, cannot use std::reverse or manually do all the work in-place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With