First, let's fix your existing code:
Your code assumes that itoa
's output ends at character 1
. Use strlen
to find the actual ending position, and then write at that position, like this:
itoa(A,C,10);
int p = strlen(C);
C[p++] = '+';
C[p++] = B;
C[p] = '\0';
Next, let's consider an alternative to this: you could use sprintf
to fit your code on a single line, like this:
sprintf(C, "%d+%c", A, B);
Finally, let's make your code C++:
Your code above might as well be in C, because it does not take advantage of C++ facilities. Both approaches above are limited, because you must pre-allocate the buffer C
at some maximum capacity. C++ gives you a stringstream
class, which lets you not worry about preallocation:
string MyAdd(int A, char B) {
stringstream ss;
ss << A << "+" << B;
return ss.str();
}