I have a simple function, that checks if the strings given match a certain condition, then generate a 3rd string based on the 2 ones received as arguments. The 3rd string is fine but when I return it it suddenly turn into “\n“.
string sReturn = "";
if (sText.size() != sPassword.size()) {
//Checks to see if the texts match a condition
return sReturn;
}
for (int foo = 0; foo < sText.size(); foo++) {
sReturn = "";
sReturn += (char)sText[foo] ^ (char)sPassword[foo];
}
return sReturn;
In the for sReturn is fine and has the right contents, but as soon as it exists the loop, the debugger suddenly tells me it’s contents are “\n“. What am I doing wrong ?
You don’t have to initialize string
with empty character array like:
Default constructor meant to do it
for you and is much more efficient.
Correct code:
Assigning an empty string to sReturn
on each iteration in your loop is
incorrect. Not to mention that to
clear a string you have to call
std::string::clear ():
Correct code:
But this should be removed from the
loop at all in your case.
There is not need to explicitly
convert the result of operator []
(size_t) into a character because it
is a character:
Correct code:
Using post-increment in for
loop is not necessary. It makes an
extra copy of the “foo” on every
increment:
This probably will be optimized by
compiler but you have to get rid of
this bad habit. Use
pre-increment instead. Correct
code:
Calling std::string::size () on
every iteration when string size
does not change is not efficient:
Better code:
Note size_t type. You cannot store
string size in 32-bit signed integer
as it has not enough capacity to
store large number. Correct type is
size_t, which is returned by
std::string::size () method.
Taking into account all above, the correct function should look something like this:
But there is a problem if you want the final string to be human-readable. Using eXclusive OR (XOR) operator on two ASCII characters might or might not give you human readable character or even an ASCII character. So you may end up having resulting string that contains newlines, unreadable characters, some garbage whatsoever.
To solve this, you have to come up with some better algorithm to generate a string basing on two other strings. For example, you may use MD5 hash of both strings or encode them in base64.
Good luck!