I have this function in Lua:
Len = function(msg, length, dir)
if not msg or not length then
return "Unknown";
end
local msgC = msg:gsub("$%d", "");
if (dir == "l") then
return string.rep(" ", length - #msgC)..msg;
else
return msg..string.rep(" ", length - #msgC);
end
end
It pads a string in the specified direction, resulting in a string that is either right-aligned or left-aligned to the number of characters specified (primarily used for formatting lists).
I tried to replicate the above function in C++:
std::string Len(string msg, int charCount, string dir)
{
int spacesRequired = (charCount-msg.length()/2);
std::ostringstream pStream;
if (dir == "l")
pStream << std::string(spacesRequired, ' ') << msg;
else
pStream << msg << std::string(spacesRequired, ' ');
return pStream.str();
}
...which doesn't work properly:
I also use a function to centre the whole string before it is printed, but that's irrelevant here since the issue is with the Len
C++ function.
What did I do wrong here, and how can I correct this?
I'm thinking the problem is my misunderstanding of local msgC = msg:gsub("$%d", "");
which (to my understanding, which may be incorrect) retrieves the length of the string. This resulted in int spacesRequired = (charCount-msg.length()/2);
which does the same as length - #msgC
.