Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 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 Reply

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 ;).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...