C++ MFC double to CString

C++ MFC double to CString

本文关键字:CString to double MFC C++      更新时间:2023-10-16

对不起我的英语。

我需要将double值转换为CString,因为我需要做AfxMessageBox(double_value);

我发现这个:

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

我该怎么做?

AfxMessageBox需要一个CString对象,因此将double格式化为CString并传递:

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

编辑:如果您希望值显示为整数(小数点后没有值),则使用以下内容:

str.Format("As string: %d", (int)double);
这是因为ost.str()不是CString,而是C++字符串对象。您需要将其转换为CString:new CString(ost.str())

根据您的Unicode设置,您需要

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

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

这是必需的,因为CString有一个const char*const wchar_t*的构造函数。没有std::string或std::wstring的构造函数。您也可以使用CString.Format,它有类似sprintf的非类型保存问题。

请注意,双重转换取决于区域设置。小数分隔符将取决于您的位置