Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am somewhat new to C++ and my background is in Java. I am working on a hdc printing method. I would like to know the best practice for concatenating a combination of strings and ints into one CString. I am using MFC's 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'. 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!

like image 553
Kyle Williamson Avatar asked Dec 06 '25 03:12

Kyle Williamson


2 Answers

If that's MFC's CString class, then you probably want Format which is a sprintf-alike for it:

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

i.e. you can assemble the string using regular printf-format specifiers substituting in the numbers at runtime.

like image 125
Rup Avatar answered Dec 09 '25 04:12

Rup


You can use also stringstream classes

#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;
}
like image 24
Alberto Boldrini Avatar answered Dec 09 '25 03:12

Alberto Boldrini