Search code examples
c++visual-studio-2010charintitoa

How to add an multidigit int and a char, where the output will be int + char


this is what I have so far

Header file reads:

    string MyAdd(int A, char B)
    {
        char C[10];
        itoa(A,C,10);
        C[1] = '+';
        C[2] = B;
        C[3] = '\0';

        return C;
    }

Calling program:

cout << "\n\t\tThe sum of 1 and X is = " << MeLoad.MyAdd(1   ,'X'   );

Where the output is:

The sum of 1 and X is = 1 + X 

But it will only work with single digit integers

so if i try to add 1000 + X, it will still return 1 + X and I have no idea why.

Can someone point me in the right direction? any help is appreciated,thanks.

Using VS 2010


Solution

  • 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();
    }