sprintf in a for loop

I made a program to do binomial expansion, but when I print the answer, it prints things like: 1x^3, 3x^0, 2x + -1 etc.

I tried to use sprintf to get the whole expansion in a string, but for some reason when I print the string at the end, I get something like this:

é é é é é 32

That was the output when I entered (3x+2)^5. I know the program works without sprintf, but I can't seem to get the whole expansion in a string. Here is the for loop that I'm using:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    char print[50] = "";
    string finalPrint = "";
    for(int ab=0;ab<=n;ab++){
        if(n-ab == 0){
            sprintf(print, "%d", coeff[n-ab]);
        }
        else if(n-ab == 1){
            sprintf(print, "%dx", coeff[n-ab]);
        }
        else{
            sprintf(print, "%dx^%d", coeff[n-ab], n-ab);
        }
        if(ab != n){
            sprintf(print, " %c ", "+");
        }
        finalPrint += print;
    }
    cout << finalPrint << endl;


n is the exponent ((ax+b)^n).

Any ideas as to how I could fix it?
Last edited on
 
sprintf(print, " %c ", "+");
Won't do what you think. You need:
 
sprintf(print, " + ");

or
 
sprintf(print, " %c ", '+');


What's the declaration of coeff?

Last edited on
Topic archived. No new replies allowed.