Domanda

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

È stato utile?

Soluzione

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

Altri suggerimenti

You are essentially misusing C++. You have high-level functionality for all what you are trying to do.

If you want to be portable to work with old compilers, I would use sstringstream for the conversion, otherwise see below.

string MyAdd(int A, char B)
{
    stringstream ss;
    ss << A << B;
    return ss.str();
}

That being said, I would personally really utilize C++11 here with to_string, so I would be writing something like this:

string MyAdd(int A, char B)
{
    return to_string(A) + B;
}

See my complete test code below.

main.cpp

#include <string>
#include <iostream>

using namespace std;

string MyAdd(int A, char B)
{
    return to_string(A) + B;
}

int main()
{
    cout << MyAdd(0, 'A') << endl;
    return 0;
}

Build and run

g++ -std=c++11 main.cpp && ./a.out

Output

0A

========================================================================

Here, you can find my pre-c++11 version if you need it for compatiblity:

main.cpp

#include <string>
#include <iostream>
#include <sstream>

using namespace std;

string MyAdd(int A, char B)
{
    stringstream ss;
    ss << A << B;
    return ss.str();
}

int main()
{
    cout << MyAdd(0, 'A') << endl;
    return 0;
}

Build and run

g++ main.cpp && ./a.out

Output

0A
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top