C++ MFC double to CString

匿名 (未验证) 提交于 2019-12-03 01:39:01

问题:

Sorry for my English.

I need to convert double value to CString, because i need to do AfxMessageBox(double_value);

I find this:

std::ostringstream ost; ost << double_value; std::cout << "As string: " << ost.str() << std::endl; //AfxMessageBox(ost.str()); - Does not work. 

How i can do this?

回答1:

AfxMessageBox expects a CString object, so format the double into a CString and pass that:

CString str; str.Format("As string: %g", double); AfxMessageBox(str); 

Edit: If you want the value displayed as an integer (no value after decimal point) then use this instead:

str.Format("As string: %d", (int)double); 


回答2:

That's because ost.str() is not a CString, but rather a C++ string object. You need to convert that to CString: new CString(ost.str()).



回答3:

Depending on your Unicode settings you need

std::ostringstream ost; ost << std::setprecision(2) << double_value; std::cout << "As string: " << ost.str() << std::endl; AfxMessageBox(ost.str().c_str()); 

or

std::wostringstream ost; ost << std::setprecision(2) << double_value; std::wcout << L"As string: " << ost.str() << std::endl; AfxMessageBox(ost.str().c_str()); 

This is needed because CString has a constructor for const char* or const wchar_t*. There is no constructor for std::string or std::wstring. You can also use the CString.Format which has the same not typesave problems like sprintf.

Be aware that double conversion is locale dependent. Decimal seperator will depend on your location.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!