我有一个使用 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/