Ok, I have created a function that is supposed to take a passed string and convert it into binary.. Since this only converts each character once, I had to create a for loop and loop through it. And in the for loop it writes the binary digit to a string stream so I can then convert that into a string and then back into a c string so I can return it. Here's my code:
1 2 3 4 5 6 7 8 9 10
constchar* BinaryConverter::Encode(string input){
constchar* _output = "";
stringstream ss(input);
for(int i=0; i<input.size(); ++i) {
ss << bitset<8>(input[i]); //create the bitset for the inputed c string
}
input = ss.str();
_output = input.c_str();
return _output; // return the c string
}
'input' is local to the Encode function. As soon a Encode returns, input is destroyed.
your '_output' pointer just points to input's data, but if input no longer exists, then its data also no longer exists.
Don't bother with char pointers. If you're returning a string, return a string:
1 2 3 4 5 6 7 8 9 10 11
string BinaryConverter::Encode(string input){ // <- return a string
// const char* _output = ""; // <- no need for this
stringstream ss(input);
for(int i=0; i<input.size(); ++i) {
ss << bitset<8>(input[i]); //create the bitset for the inputed c string
}
// input = ss.str();
// _output = input.c_str();
// return _output;
return ss.str(); // <-just return the string. Problem solved
}
You are returning a const char pointer to the internal buffer of an object that has been destroyed by the time your function returns:
1 2
_output = input.c_str();
return _output; // return the c string
The std::string input gets destroyed after the return statement and so the value you return is invalid. It may or may not still point to the data in the string. It is what we call 'undefined behaviour' (UB).
In C++ it is generally better to return a std::string rather than a const char* because pointers need to be deleted by someone. So I would recommend returning a std::string, not a pointer.
Also you create your std::stringstream with the input already in it before you then send your output to it. I think you probably just wanted to place the output in the std::stringstream.
I would probably use a std::ostringstream:
1 2 3 4 5 6
std::ostringstream oss; // collect binary output
for(std::string::size_type i = 0; i < input.size(); ++i)
{
oss << std::bitset<8>(input[i]); //create the bitset for each character of input
}
Also you pass in your input by value. That means that your input string is copied into the function. There is no need to do this, it may be more efficient to pass in a const reference like this:
1 2 3 4 5 6
std::string encode(const std::string& input)
{
// ...
return oss.str(); // return the output as a std::string
}