与 MFC 的 CString 连接最合适的方式是什么

What is the most appropriate way to concatenate with MFC's CString

本文关键字:方式 是什么 连接 MFC CString      更新时间:2023-10-16

我对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,则可以使用ostringstreamboost::lexical_cast