首页 > 解决方案 > 在 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(),它将写入刚刚写入的字符串上方。有什么解决办法吗?

标签: c++c++11winapi

解决方案


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

推荐阅读