windows 下控制台只能输入或输入输出的问题
首先,你要知道,
std::string
这东西高级得很,由于重载了运算符的的原因
std::cout
可以输出任何编码的东西,通常里来说 GBK 只能输入,UTF8 只能输出(只能写入 UTF8 文件),那我们直接融合一下不就好了?
本节讲 c++23, c++14 有其他的函数。
首先是,输入时采用 GBK 编码。
set_GBK();
std::cin >> s;
// std::cout << s << " " << s.size();
然后,我们直接转换字符串:
s = gbk_to_utf8(s);
再输出:
set_UTF8();
std::cout << s << " " << s.size();
其中函数的实现:
#include <bits/stdc++.h>
#include <windows.h>#ifndef _STRING_FORMATstd::string utf8_to_gbk(const std::string& utf8_str) {// UTF-8 到宽字符(UTF-16)int wide_size = MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, nullptr, 0);if (wide_size == 0) {return "";}std::wstring wide_str(wide_size, L'\0');if (MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, wide_str.data(), wide_size) == 0) {return "";}// 宽字符到 GBKint gbk_size = WideCharToMultiByte(CP_ACP, 0, wide_str.c_str(), -1, nullptr, 0, nullptr, nullptr);if (gbk_size == 0) {return "";}std::string gbk_str(gbk_size - 1, '\0');if (WideCharToMultiByte(CP_ACP, 0, wide_str.c_str(), -1, gbk_str.data(), gbk_size, nullptr, nullptr) == 0) {return "";}return gbk_str;
}std::string gbk_to_utf8(const std::string& gbk_str) {// GBK 到宽字符(UTF-16)int wide_size = MultiByteToWideChar(CP_ACP, 0, gbk_str.c_str(), -1, nullptr, 0);if (wide_size == 0) {return "";}std::wstring wide_str(wide_size, L'\0');if (MultiByteToWideChar(CP_ACP, 0, gbk_str.c_str(), -1, wide_str.data(), wide_size) == 0) {return "";}// 宽字符到 UTF-8int utf8_size = WideCharToMultiByte(CP_UTF8, 0, wide_str.c_str(), -1, nullptr, 0, nullptr, nullptr);if (utf8_size == 0) {return "";}std::string utf8_str(utf8_size - 1, '\0');if (WideCharToMultiByte(CP_UTF8, 0, wide_str.c_str(), -1, utf8_str.data(), utf8_size, nullptr, nullptr) == 0) {return "";}return utf8_str;
}void set_GBK() {SetConsoleOutputCP(936); // 设置输出代码页为 GBKSetConsoleCP(936); // 设置输入代码页为 GBK
}void set_UTF8() {SetConsoleOutputCP(65001); // 设置输出代码页为 UTF8SetConsoleCP(65001); // 设置输入代码页为 UTF8
}#define _STRING_FORMAT
#endif
这样就可以完美的使用啦