C ++如何仅在一定时间内读取输入?我可以在用户不按回车键的情况下这样做吗?

C++ How do I read in input for a certain amount of time only? Can I do so without the user pressing enter?

对于我正在编写的程序,我希望使用 cin 从键盘读取字符,直到经过一定时间。用户可以输入任意数量的字符(从 0 到尽可能多的字符),程序需要将字符存储在数组中以备后用。理想情况下,用户不必在每个字母后按回车键;该程序应该能够在没有任何换行符的情况下读取输入,并在指定时间结束后停止。我已经寻找了一段时间并尝试了不同的方法,包括使用 getline、usleep,甚至 SDL,但我尝试过的方法都没有用。这是我最近的尝试:

#include <iostream>     
using namespace std;

#include <time.h>

const float frame_length = 1;

int main () {

    char test[40];

    clock_t t;
    t = clock();
    int counter = 0;

    while (clock() - t < (1000000 * frame_length)){
        cin >> test[counter];
        counter ++ ;
    }

     cout << endl << "STOP" << endl;
}

这里的问题是循环在指定的时间后根本没有停止(当我用 cout 行替换 cin 行时它确实停止了)并且用户仍然需要每次按 enter 键。是否可以按照我希望的方式读取输入?如果有帮助,我正在研究 Mac。任何帮助将非常感激。

既然你说了 deally, the user should not have to press enter after each letter; the program should be able to read in the input without any line breaks,你的程序将无法满足上述要求,因为 std::cin 会阻塞当前线程,直到用户按下 ENTER 键。你能做的就是持续监控关键状态。如果在给定时间内按下了某个键,则将该字符添加到您的测试数组中。如果你在 windows 环境中,你可以使用 GetAsycKeyState 函数来达到这个目的。

这里是修改后的代码,

#include <iostream>


#include <Windows.h>
#include <time.h>

const float frame_length = 1;

using namespace std;
int main () {

    char test[40];

    clock_t t;
    t = clock();
    int counter = 0;

    while (clock() - t < (3000 * frame_length)){

        //cin >> test[counter];

        //i have added Sleep(200) here to prevent    
        //picking up a single key stroke as many key strokes.
        Sleep(200);

        for(int key = 0x41; key < 0x5a; key++)
        {
            if(GetAsyncKeyState(key))
            {
                test[counter] = char(key);
                cout << char(key) << endl;
                counter ++ ;

                break;
            }

        }




    }


    cout << endl << "STOP" << endl;
}