为什么CancelIoEx没有完全取消getline,需要两次回车才能触发下一个getline?

问题描述 投票:0回答:1

这是一个 C++ 示例。

每隔 7 秒,会调用

CancelIoEx()
,用户需要填写两次内容(按两次 Enter 键)才能触发
getline()

我猜 Windows 控制台中的某些内容可能无法被

CancelIoEx()
正确取消,可能会导致此问题?

#include <iostream>
#include <thread>
#include <string>
#include <windows.h>

using namespace std;
HANDLE hStdin = nullptr;

void readInput() {
    string input;
    while (true) {
        cout << endl << "input: ";
        getline(std::cin, input);
        if (cin.good())
            cout << "got msg: " << input << std::endl;
        else
        {
            cin.clear();
        }
    }
}

void CancelInputPeriodically() {
    while (true) {
        this_thread::sleep_for(std::chrono::seconds(7));
        CancelIoEx(hStdin, nullptr);
        cout << "time's up!!!" << endl;
    }
}

int main() {
    hStdin = GetStdHandle(STD_INPUT_HANDLE);
    thread cancelThread(CancelInputPeriodically);

    readInput();

    cancelThread.join();
    return 0;
}

我尝试在

getline()
设置断点,但它确实没有收到我的第一个 Enter 键。

解决方法是使用

WriteConsoleInput()
在 cin EOF 之后发送
VK_RETURN

c++ windows console cancelio
1个回答
0
投票

CancelIoEx
是 Windows 功能。它取消其他 Windows IO 调用。它不保证 Visual Studio 标准库实现中有关
std::getline
的任何信息。

Visual Studio 标准库中没有与

CancelIOEx
等效的东西。如果您需要,您需要从
streambuf
重新实现
std::cin
以获得有保证的结果。但这对你来说会很棘手,因为问题表明你不熟悉这里的分层结构。

© www.soinside.com 2019 - 2024. All rights reserved.