C++ MFC double 到 CString

Posted

技术标签:

【中文标题】C++ MFC double 到 CString【英文标题】:C++ MFC double to CString 【发布时间】:2013-06-23 09:07:30 【问题描述】:

对不起我的英语。

我需要将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? AfxMessageBox 不期望双... @zmbq 没有 AfxMessageBox(double_value);不建议它期望双倍? AfxMessageBox 需要 CString: AfxMessageBox("Text");它不是双重的 实际上 AfxMessageBox 需要 LPCTSTR,而不是 CString,但后者有很好的隐式转换,所以它可以工作。您的试用意味着您有 UNICODE 配置,是什么导致了错误。您可以使用 AfxMessageBoxA 代替 AfxMessageBox。当然使用接受的答案也可以。 【参考方案1】:

AfxMessageBox 需要 CString 对象,因此将双精度格式设置为 CString 并传递:

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

编辑:如果您希望将值显示为整数(小数点后没有值),请改用:

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

【讨论】:

非常感谢,这是工作。如果您知道,请告诉我如何裁剪/剪切 CString 的一部分。我有 12.09 的值,我需要 12 的值。 使用%d而不是%g,它应该给你整数值。 %d 给我这个:作为字符串:-1546188226 @user2254511 你的问题解决了吗? (转换为int 是关键)。【参考方案2】:

那是因为 ost.str() 不是一个 CString,而是一个 C++ 字符串对象。您需要将其转换为 CString:new CString(ost.str())

【讨论】:

对不起,我是初学者 CString sss = new CString(ost.str());不工作【参考方案3】:

取决于您需要的 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 相同的非类型保存问题。

请注意,双重转换取决于语言环境。小数分隔符将取决于您的位置。

【讨论】:

以上是关于C++ MFC double 到 CString的主要内容,如果未能解决你的问题,请参考以下文章

C++ MFC CString怎么转换成Double

从 CString C++ 中删除特定行

MFC结构数组

非 MFC 应用程序中的 MFC 对话框

如何将 ATL/MFC CString 转换为 QString?

C++ string 转化为LPCTSTR