简体   繁体   English

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

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

I am somewhat new to C++ and my background is in Java. 我对C ++有点新,我的背景是Java。 I am working on a hdc printing method. 我正在研究hdc打印方法。 I would like to know the best practice for concatenating a combination of strings and ints into one CString. 我想知道将字符串和整数组合连接成一个CString的最佳实践。 I am using MFC's 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);

I would like it to look like 'Page 1 of 2'. 我希望它看起来像'第1页,共2页'。 My current code does not work. 我目前的代码不起作用。 I am getting the error: 我收到错误:

Expression must have integral or enum type 表达式必须具有整数或枚举类型

I have found more difficult ways to do what I need, but I want to know if there is a simple way similar to what I am trying. 我找到了更困难的方法来做我需要的东西,但我想知道是否有一种类似于我正在尝试的简单方法。 Thanks! 谢谢!

If that's MFC's CString class , then you probably want Format which is a sprintf-alike for it: 如果那是MFC的CString类 ,那么你可能想要一个类似sprintf的Format

CString pages;
pages.Format(_T("Page %d of %d"), i, maxPage);

ie you can assemble the string using regular printf-format specifiers substituting in the numbers at runtime. 即你可以使用常规printf格式说明符组装字符串,在运行时替换数字。

std::string has all you need: std::string拥有你所需要的一切:

auto str = "Page " + std::to_string(i) + " of " + std::to_string(maxPage); 

As stated correctly in the comment, you can access the underlying C-string via str.c_str() . 正如注释中所述,您可以通过str.c_str()访问底层C字符串。 Here is a live working example. 是一个实际工作的例子。

You can use also stringstream classes 您也可以使用stringstream类

#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;
}

If you have C++11 you can use std::to_string : std::string pages = std::string("Page ") + std::to_string(i) + (" of ") + std::to_string(maxPage); 如果你有C ++ 11,你可以使用std::to_stringstd::string pages = std::string("Page ") + std::to_string(i) + (" of ") + std::to_string(maxPage);

If you don't have C++11 you can use an ostringstream or boost::lexical_cast . 如果你没有C ++ 11,你可以使用ostringstreamboost::lexical_cast

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM