In this post, we will see how to resolve Strcat not appending a character
getMinute(). However, I need to check if one of these two are less than 10: if so, I need to append a 0 so that the output is such that:
My problem is that it does not append the
:character. For instance, if
getHour() = 9and
getMinute() = 15. The output of
09:15. Do you have any idea why this is like this?
Best Answer:To begin with,
strcat("0",hour)will lead to undefined behavior as you attempt to modify the literal string
"0"which isn’t allowed.
Instead of using multiple
strcatcalls, why not simply create a string large enough to fit the result, and use
snprintfto put contents into the string?
snprintfwill also make it easier to optionally add a zero-prefix to the hour value.
Perhaps something like this:
resultarray as an argument to the function. The would handle ownership of the
resultarray better, and might not even need dynamic allocation.
[Note that the above is a pure C solution, it’s not even valid in C++. I wrote it before noticing that the code in the question is really C++.]
Considering that you really seem to be programming in C++, not C, then a solution using string streams and
std::stringwould be more appropriate:
If you have better answer, please add a comment about this, thank you!