简体   繁体   English

使用CString的MFC TextOut失败

[英]MFC TextOut using CString fails

I use MFC TextOut to put some text on screen as follows 我使用MFC TextOut在屏幕上放置一些文本,如下所示

std::string myIntToStr(int number)
{
    std::stringstream ss;//create a stringstream
    ss << number;//add number to the stream
    return ss.str();//return a string with the contents of the stream
}


void MViewClass::DrawFunction()
{
    CClientDC aDC(this);
    // .. Drawing Code
    aDC.TextOut(27, 50, ("my age is " + myIntToStr(23)).c_str());

}

But I get error saying " cannot convert argument 3 from 'const char *' to 'const CString &'". 但是我收到错误消息,说“无法将参数3从'const char *'转换为'const CString&'”。

The documentation for TextOut shows a CString overload. TextOut的文档显示了CString重载。 I would like to use CString with TextOut as it allows me to use my myIntToStr converter. 我想将CString与TextOut一起使用,因为它允许我使用myIntToStr转换器。 Any suggestions? 有什么建议么?

The code uses std::string's c_str , which returns const char* , not CString`. 该代码使用std::string's c_str , which returns const char * , not CString`。 Try 尝试

void MViewClass::DrawFunction()
{
    CClientDC aDC(this);
    CString s("my age is ");
    s += myIntToStr(23).c_str();
    // .. Drawing Code
    aDC.TextOut(27, 50, s);
}

or just use CString::Format 或只使用CString :: Format

void MViewClass::DrawFunction()
{
    CClientDC aDC(this);
    CString s;
    s.Format("my age is %d", 23);
    // .. Drawing Code
    aDC.TextOut(27, 50, s);
}

I assume that you use function myIntToStr to convert an int to a string elsewhere in you code, and that you current problem is how to display a C++ string with TextOut. 我假设您使用函数myIntToStr将int转换为代码中其他位置的字符串,并且当前的问题是如何使用TextOut显示C ++ string

You could simply create a CString in the stack initialized from the std::string that way : 您可以这样简单地在从std::string初始化的堆栈中创建一个CString:

void MViewClass::DrawFunction()
{
    CClientDC aDC(this);
    // .. Drawing Code
    CString age(("my age is " + myIntToStr(23)).c_str());
    aDC.TextOut(27, 50, age);

}

As it is created on the stack, it will automatically vanish at the end of the method and you have not worry about allocation and deallocation. 当它在堆栈上创建时,它将在方法结束时自动消失,而您不必担心分配和释放。

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

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