Search code examples
c++windowgditextout

c++ issue with the TextOut() gdi function LPCSTR parameter


I am trying to use the TextOut function to paint words on my window, and the following method works fine for me:

HDC hdc = GetDC(windowHandle);
TextOut(hdc, 10, 10, TEXT("Hello World"), 16);
ReleaseDC(windowHandle, hdc);

And this outputs :Hello World

All good so far, however when I do the following method:

HDC hdc = GetDC(windowHandle);
string myString = "Hello World";
TextOut(hdc, 10, 10, myString.c_str(), 16);
ReleaseDC(windowHandle, hdc);

the program outputs: Hello World#$%^&

and the #$%^& part are actually other square symbols that I am not sure how to write on the keyboard. I understand that the forth parameter of the TextOut function is type LPCSTR, and using the .c_str() function after my string should output the LPCSTR variable correctly, and so it does since the program runs, however why do I get teh #$%^& included at the end of Hello World and how might I go about fixing that issue? I do need to use the second method and not the first because my program will generate strings which then I would like to output to my window.


Solution

  • According to the documentation of TextOut (http://msdn.microsoft.com/en-us/library/windows/desktop/dd145133%28v=vs.85%29.aspx) the fith parameter reflects the length of the string. You are saying 16 here, however, it's only 11.