Conni Bilham
Conni Bilham

Reputation: 37

changing const wchar_t* during runtime

i have a string that i recieve from using std::cin and im trying to change a const wchar_t* to that variable

const wchar_t* TARGET_FILE = L"";
try {
    std::string str;
    std::cout << "DLL Name: ";
    getline(std::cin, str);
    //TARGET_FILE = str;
    std::string narrow_string(str);
    std::wstring wide_string = std::wstring(narrow_string.begin(), narrow_string.end());
    const wchar_t* result = wide_string.c_str();
    const wchar_t* TARGET_FILE = result;
    std::cout << TARGET_FILE; //Debug

}
catch (const std::exception & ex) {
    std::cout << "[ERROR] " << ex.what() << '\n';
    std::cout << "Press any key to exit..." << '\n';
    std::cin.get();
    return EXIT_FAILURE;
}

When this code is executed this is what happens

DLL Name: Kinky.dll
0000020E11C61560[ERROR] DLL not found.
Press any key to exit...

i get 0000019CCB971300 instead of a valid text format it works when i hard code the value of TARGET_FILE using

//constexpr auto TARGET_FILE      = L"Kinky.dll";

Sorry if im being a bit stupid but im not very familiar with what wchar_t vars are i just know the sdk im using requires one

Edit: This section was pasted by me to try resolve the original issue so idk if its the correct usage if its not the correct usage im expecting this to be my issue

std::string narrow_string(str);
std::wstring wide_string = std::wstring(narrow_string.begin(), narrow_string.end());
const wchar_t* result = wide_string.c_str();
const wchar_t* TARGET_FILE = result;

Upvotes: 0

Views: 563

Answers (2)

smitsyn
smitsyn

Reputation: 722

Two problems:

1) The potential problem is how you convert narrow to wide string. While you convert ASCII dll names everything is fine (or not? Only in practice I guess?). Otherwise there be dragons. Converting to wide characters is hard: you should somehow know the narrow encoding (UTF-8? System encoding?), wide characters encoding is also different on different platforms (USC-2 or UTF-16 on Windows, UTF-32 on Linux, native endianness). But this is different concern.

2) Correct answer (mentioned by @Ville-Valtteri) is that you cannot output const wchar* to std::cout. cout treats it as a pointer, and this 00007FF6A958CAF0 thing that you get is a pointer value. This is not what you want. Maybe you want to write to std::wcout, or convert back to narrow string; what you need depends on your actual real code.

Upvotes: 2

VLL
VLL

Reputation: 10165

Instead of converting the string, you can read wide characters to begin with. Use std::wcin to read and std::wcout to print wide characters. You can keep the text as std::wstring and use c_str() when you call the function which requires const wchar_t*.

void function1(const wchar_t*);

void function2() {
    std::wstring str;
    getline(std::wcin, str);
    std::wcout << str;

    function1(str.c_str());
}

Upvotes: 5

Related Questions