0

When I compile and link the following program, it doesn't show me any issue.

#include <Windows.h>
#include <iostream>

int main(int argc, const char* argv)
{
    std::string cMessage = "Native Windows Development.\n";
    WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), cMessage.c_str(), cMessage.size(), NULL, NULL);

    return 0;
}

But when I execute the program, it shows me just a bunch of ????? sign in the console. what is the problem with the code? Why I can't use std::string rather const char* ?

1
  • 1
    Try changing the function name to WriteConsoleA. Commented Feb 24, 2020 at 20:19

2 Answers 2

2

The ? output indicates that you are compiling for Unicode, where WriteConsole() maps to WriteConsoleW(). Since you are wanting to write char data, use WriteConsoleA() instead:

#include <Windows.h>
#include <iostream>

int main(int argc, const char* argv)
{
    std::string cMessage = "Native Windows Development.\n";
    WriteConsoleA(GetStdHandle(STD_OUTPUT_HANDLE), cMessage.c_str(), cMessage.size(), NULL, NULL);

    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

0

By default, the character set is Unicode so WriteConsole expects a wchar string. You have two choices.

1) Do everything in unicode

int main(int argc, const char* argv)
{
    std::wstring cMessage = L"Native Windows Development.\n";
    WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), cMessage.c_str(), cMessage.size(), NULL, NULL);

    return 0;
}

2) Set the default character set to mbcs

3 Comments

There is a third choice, as I mentioned above.
That is what changing the character set to mbcs will do
Your first choice is wrong. If you want to "do everything in Unicode", the signature of the entry point is wmain(int argc, wchar_t* argv[]).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.