C++/Converting a double to a string...
Expert: Eddie - 2/1/2008
QuestionQUESTION: Hi again Eddie,
I need to enter a double into an edit box. Is there a way to accurately convert a double to a string for this purpose?
Also, is there a way to round off this double to 4 decimal places?
Thanks in advance for your help,
-Neil
ANSWER: Hello Neil, thank you for the question.
Sure, C++ provides an easy mechanism for this called ostringstream. Here is some sample code:
double d = 0.123456789;
std::ostringstream oss;
oss << d;
std::string value = oss.str();
This inserts the value d into the stream, and then returns the string value by calling .str(), which you can use to display.
Setting the precision is the same as always.
std::cout << setprecision(2) << value << std::endl;
This should do what you're looking for.
I hope this information is helpful.
- Eddie
---------- FOLLOW-UP ----------
QUESTION: Hi again, Eddie,
I'm still having trouble placing this string(value) into the text box. The only reference one of my books on VisualC++ 6 gives is below and doesn't work because: binary '=' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocat.
Is there a better way to enter this std::basic string into an edit box than below?
CString strText;
strText=value;
CEdit* pStrValue = (CEdit*)GetDlgItem(IDC_EDIT_BOX);
pStrValue->SetWindowText(strText);
Thanks in advance for your help,
-Neil
AnswerHello Neil, thank you for the question.
From what I understand you have a std::string called value, which contains the double you want to put in the edit box, correct?
I'm not much of a MFC person, however, from what I've read online you should be able to assign a const char* to a CString using the _T macro to translate. I don't know if you know this already so I'll say it. You can get the const char* C style string from a std::string by called .c_str():
CString strText = _T(value.c_str());
That should return the const char* string and translate it to a CString with the _T macro.
http://msdn2.microsoft.com/en-us/library/8a994dfk.aspx
There is a link that explains it.
Let me know if this works for you.
I hope this information was helpful.
- Eddie