c++ - 在运行时更改 const wchar_t*

标签 c++

我有一个使用 std::cin 收到的字符串,我正在尝试将 const wchar_t* 更改为该变量

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;
}

当这段代码被执行时,会发生这样的事情

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

我得到 0000019CCB971300 而不是有效的文本格式,当我使用硬编码 TARGET_FILE 的值时它起作用

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

抱歉,如果我有点愚蠢,但我不太熟悉什么是 wchar_t 变量,我只知道我使用的 sdk 需要一个

编辑: 这部分是我粘贴的,目的是尝试解决原始问题,所以我知道它的用法是否正确,如果用法不正确,我希望这是我的问题

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::wcin 读取并使用 std::wcout 打印宽字符。您可以将文本保留为 std::wstring 并在调用需要 const wchar_t* 的函数时使用 c_str()

void function1(const wchar_t*);

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

    function1(str.c_str());
}

关于c++ - 在运行时更改 const wchar_t*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58856548/

相关文章:

c++ - 程序在启动后立即以退出状态 0 退出

c++ - 从 asio::ip::tcp::socket 直接写入 std::string

c++ - 更改 Xbox Controller 代表哪个玩家?

c++ - 是否在 C++ 中使用 double() 函数?

c++ - 具有特定顶点类型的图的序列化

c++ - 我可以在不声明变量类型的情况下获取输入或在 C++ 中为同一变量声明多个类型吗?

c++ - 如何在 C++ 中有效地将整个队列复制到 vector/数组?

c++ - 指向 vector 中项目的指针是不稳定的。

c++ - 强制一个特定的构造函数只在某些代码中使用,别处

c++ - gcc segmentation fault - 我怎样才能找到它发生的地方?