Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

How to convert a double variable into a char array in C++?

I'm working on a project for school and we just found out that outtextxy() (a function from graphics.h, which we must use) requires as the text parameter a char array. Here is it's declaration: void outtextxy (int x, int y, char *textstring)

The issue is that we need to print out a number of type double, including the decimal point. I have previously tried making it work using knowledge from other similar questions, but none has worked.

Here are is my latest attempt, which resulted in a Segmentation Fault:

char *DoubleToString(long double x)
{
    char s[256]="00";

    std::ostringstream strs;
    strs << x;
    string ss = strs.str();

    for(int i=0; i < ss.length(); i++)
        s[i] = ss[i];
    return s;
}

NOTE: I am still somewhat new to programming and I don't exactly know what ostringstream and the bitshift-looking operation are doing, but I tried to copy-paste that part in hopes of it working.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

... requires as the text parameter a char array.

Ok, then use a std::string:

std::string DoubleToString(long double x)
{
    std::ostringstream strs;
    strs << x;
    return strs.str();
}

If you need the underlying character array use the strings data() method. It does return a pointer to the first element of the strings character array. For example:

std::string s = DoubleToString(3.141);
function_that_needs_pointer_to_char( s.data() );

Note that before C++17 data returned a const char* (and since C++11 the character array is null-terminated, as one would expect ;).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...