与 MFC 的 CString 连接最合适的方式是什么
What is the most appropriate way to concatenate with MFC's CString
我对C++有些陌生,我的背景是Java。我正在研究一种hdc打印方法。我想知道将字符串和int的组合连接到一个CString中的最佳实践。我正在使用MFC的CString。
int i = //the current page
int maxPage = //the calculated number of pages to print
CString pages = ("Page ") + _T(i) + (" of ") + _T(maxPage);
我希望它看起来像"第1页,共2页"。我当前的代码不起作用。我得到错误:
表达式必须具有整数或枚举类型
我找到了更困难的方法来做我需要的事情,但我想知道是否有一种简单的方法与我正在尝试的类似。谢谢
如果这是MFC的CString类,那么您可能想要Format
,它与sprintf类似:
CString pages;
pages.Format(_T("Page %d of %d"), i, maxPage);
即,您可以在运行时使用替换数字的常规printf格式说明符来组装字符串。
您也可以使用字符串流类
#include <sstream>
#include <string>
int main ()
{
std::ostringstream textFormatted;
textFormatted << "Page " << i << " of " << maxPage;
// To convert it to a string
std::string s = textFormatted.str();
return 0;
}
std::string
具备您所需的一切:
auto str = "Page " + std::to_string(i) + " of " + std::to_string(maxPage);
正如注释中正确指出的,您可以通过str.c_str()
访问底层的C字符串。这是一个实际工作的例子。
如果您有C++11,您可以使用std::to_string
:std::string pages = std::string("Page ") + std::to_string(i) + (" of ") + std::to_string(maxPage);
如果您没有C++11,则可以使用ostringstream
或boost::lexical_cast
。
相关文章:
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- 在reactor中存储eventHandlers的最佳方式是什么
- 引用 std::any 或 not_yet_in_std::whatever 的惯用方式是什么?
- 在C++中,建议通过数组循环的方式是什么?
- DLL共享数据的推荐方式是什么
- 等待线程的最佳方式是什么
- 将uint8_t*buffer和size_tbufferlen从C++传递到C中的API函数的最佳方式是什么
- 只显示片段着色器的最佳方式是什么
- 复制文件的最佳方式是什么,以便我可以在复制过程中轻松取消复制?
- 在 c++ 中打印到控制台的最佳方式是什么?
- 在Qt Creator中应用代码更改的快捷方式是什么?
- 在C 中超负荷构造函数的合适方式是什么
- 执行随机开关函数的QT方式是什么连续两次使用相同情况的方法
- 在某些代码中覆盖方法的方式是什么?
- 为单个函数同时声明多个变量的最佳方式是什么
- Qt中数据类(模型)和视图/控制器类之间的数据通信的正确方式是什么
- 在c++中存储一个对象或不存储对象的首选方式是什么
- 在C 项目中包含库的不同方式是什么?
- 解释"Bit String"的最佳方式是什么
- 计算差异数据并通过网络发送的最佳方式是什么