I would like to know how to change the console title in C++ using a string as the new parameter.
I know you can use the SetConsoleTitle
function of the Win32 API but that does not take a string parameter.
I need this because I am doing a Java native interface project with console effects and commands.
I am using windows and it only has to be compatible with Windows.
The SetConsoleTitle
function does indeed take a string argument. It's just that the kind of string depends on the use of UNICODE or not.
You have to use e.g. the T
macro to make sure the literal string is of the correct format (wide character or single byte):
SetConsoleTitle(T("Some title"));
If you are using e.g. std::string
things get a little more complicated, as you might have to convert between std::string
and std::wstring
depending on the UNICODE
macro.
One way of not having to do that conversion is to always use only std::string
if UNICODE
is not defined, or only std::wstring
if it is defined. This can be done by adding a typedef
in the "stdafx.h"
header file:
#ifdef UNICODE
typedef std::wstring tstring;
#else
typedef std::string tstring;
#endif
If your problem is that SetConsoleTitle
doesn't take a std::string
(or std::wstring
) it's because it has to be compatible with C programs which doesn't have the string classes (or classes at all). In that case you use the c_str
of the string classes to get a pointer to the string to be used with function that require old-style C strings:
tstring title = T("Some title");
SetConsoleTitle(title.c_str());
There's also another solution, and that is to use the explicit narrow-character "ASCII" version of the function, which have an A
suffix:
SetConsoleTitleA("Some title");
There's of course also a wide-character variant, with a W
suffix:
SetConsoleTitleW(L"Some title");