how use sprintf() with string?

how use sprintf() with string?
i have these function for format the numbers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
  string FormatNumber(double dbltext, string textformat)
{
    string text=to_string(dbltext);
    string outputtext="";
    int intFormat=0;
    int inttext=0;
    for(intFormat=0,inttext=0; intFormat<textformat.size() or inttext<text.size(); intFormat++,inttext++)
    {
        if(textformat[intFormat]=='#')
            outputtext+=text[inttext];
        else
        {
            outputtext+=textformat[intFormat];
            inttext=inttext-1;
        }
    }
    //getting the count of numbers and zeros for right and left
    int intdecimal=0;
    int intnodecimal=0;
    bool blndecimaldot=false;
    for(int i=0; i<textformat.size(); i++)
    {
        if(textformat[i]=='#' and blndecimaldot==false)
            intnodecimal+=1;
        else if(textformat[i]=='.' or textformat[i]==',')
                 blndecimaldot=true;
        else if (textformat[i]=='#' and blndecimaldot==true)
            intdecimal+=1;
    }

    //give the zeros on tight and left
    char *chrtext;
    string format=(string)"%0"+to_string(intnodecimal)+ "." + to_string(intdecimal)+"f";
    MessageBox(NULL,format.c_str(),"testing", MB_OK);


    double mycharp =atof(outputtext.c_str());

    const char *myformatp =format.c_str();
    MessageBox(NULL,to_string(mycharp).c_str(),"testing", MB_OK);
    //chrtext2=outputtext.c_str();
    sprintf(chrtext,myformatp,mycharp);

    //getting the final result for return it
    outputtext=chrtext;

    return outputtext;
}

but i get a memory leak.
the sprintf() isn't recive, correctly, the values :(
can anyone advice me?
This code is a disaster. What are you trying to accomplish, exactly?
format a number:
see these number:
95.25
now imagine these output format:
###.###
the output must be:
095.250
osucs1: please keep this thread open for proper discussion of the code. offtopic chatter is not neccesary here.
Something like this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <cmath>
#include <iomanip>
#include <iostream>
#include <sstream>

std::string format(double value, const std::string& fmt)
{
    const std::size_t dot_pos = fmt.find('.');

    std::size_t min_integer_width = dot_pos == std::string::npos ? fmt.size() : dot_pos;
    std::size_t fractional_width = dot_pos == std::string::npos ? 0 : fmt.size() - dot_pos - 1;

    std::ostringstream os;

    os << std::setfill('0') << std::right;

    if (value < 0.0)
        os << '-';

    os << std::setw(min_integer_width + fractional_width + 1);
    os << std::fixed << std::setprecision(fractional_width);
    os << std::abs(value);
   
    return os.str();
}


yes.. thanks for all
Topic archived. No new replies allowed.