c++ - 在 WriteConsole 之后 Win32 API 控制台光标不移动
问题描述
因此,当我尝试使用此代码从控制台读取 std::wstring
std::wstring string;
wchar_t c;
DWORD u;
do {
ReadConsole(GetStdHandle(STD_INPUT_HANDLE), &c, 1, &u, NULL);
} while (u && (c == L' ' || c == L'\n'));
do {
string.append(1, c);
ReadConsole(GetStdHandle(STD_INPUT_HANDLE), &c, 1, &u, NULL);
} while (u && c != L' ' && c != L'\n');
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), string.data(), string.length(), &u, NULL);
写入字符串后,光标位置不会移动,因此如果我再次调用 WriteConsole(),它将写入刚刚写入的字符串上方。有什么解决办法吗?
解决方案
当ReadConsole
读取标准输入时,它会附加\r\n
到字符串中。您只排除\n
了条件。"string\r"
将传递给WriteConsole
,并将\r
光标返回到行首。试试下面的代码:
#include <windows.h>
#include <iostream>
#include <string>
int main(int argc, char** argv)
{
std::wstring string;
wchar_t c;
DWORD u;
do {
ReadConsoleW(GetStdHandle(STD_INPUT_HANDLE), &c, 1, &u, NULL);
} while (u && (c == L' ' || c == L'\n'));
do {
string.append(1, c);
ReadConsoleW(GetStdHandle(STD_INPUT_HANDLE), &c, 1, &u, NULL);
} while (u && c != L' ' && c != L'\n' && c != L'\r');
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), string.data(), string.length(), &u, NULL);
return 0;
}
推荐阅读
- azure - Azure 事件网格 api 版本未定义
- asp.net - 单选按钮列表故障
- reactjs - FormBuilder react-formio 默认值
- django - Django ManyToManyField 持久性失败
- python - 如何将所有参数传递给 self 并删除 args?
- unity3d - ARCore 增强图像不在外部跟踪
- delphi - 为什么不继承本地类型声明?
- r - 如何使用 geom_smooth (ggplot2) 表示变化点趋势之前/之后
- python - PyTorch - 另一个张量中对应值的索引
- node.js - NGNIX 反向代理默认设置