在C中使用SCANF功能一段时间

发布于 2025-02-11 11:43:50 字数 75 浏览 2 评论 0原文

我程序的要求是,它应该移至下一行,而无需等待用户在使用scanf()时输入。用户必须在此期间内输入输入。 我能做什么,我的程序不断执行?

The requirement of my program is, it should move to next line without waiting for the user to enter while using Scanf(). The user have to enter the input within that period of time.
What I can do so that my program execute continuously?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静水深流 2025-02-18 11:43:50

我不记得任何独立平台的方法可以通过Scanf()获取您想要的东西,但是有特定于平台的方法。

如果您使用的是Windows,则可以使用< Windows.h>控制台API获取非阻止输入。

定义一个函数以获取用户的单个字符输入,该字符输入在用户按任何键后立即退出。

#include <windows.h>

TCHAR ourgetch(HANDLE ipHandle) {
    DWORD con_mode, byteswritten;
    GetConsoleMode(ipHandle, &con_mode);
    SetConsoleMode(ipHandle, con_mode & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT));
    TCHAR ch = 0;
    ReadConsole(ipHandle, 
                &ch, 1, 
                &byteswritten, NULL);
    SetConsoleMode(ipHandle, con_mode);
    return ch;
}

现在,您可以将其用于主循环中以获取输入字符串。

char* getInput () {
  char buff[1000];
  int i = 0;
  while (! some_global_timer_flag) {
    key = ourgetch(ipHandle);
    buff[i++] = key;
  }
  return buff;
}

int main () {
  HANDLE ipHandle = GetStdHandle(STD_INPUT_HANDLE);

  char* buffer = getInput();
  // use buff
}

然后,您可以使用首选的多线程API来在线程中运行getInput(),而使用timer() thread具有全局标志,该grenga将中断并在时间时结束输入up,getInput()正在接受输入。

I do not recall any platform independent method to get what you are looking for with scanf(), But there are platform specific ways.

If you are using Windows you can make use of the <windows.h> console api for getting non blocking input.

Define a function to get a single character input from user which immediately quits after the user presses any key.

#include <windows.h>

TCHAR ourgetch(HANDLE ipHandle) {
    DWORD con_mode, byteswritten;
    GetConsoleMode(ipHandle, &con_mode);
    SetConsoleMode(ipHandle, con_mode & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT));
    TCHAR ch = 0;
    ReadConsole(ipHandle, 
                &ch, 1, 
                &byteswritten, NULL);
    SetConsoleMode(ipHandle, con_mode);
    return ch;
}

And now you can use that in your main to call it in a loop to get an input string.

char* getInput () {
  char buff[1000];
  int i = 0;
  while (! some_global_timer_flag) {
    key = ourgetch(ipHandle);
    buff[i++] = key;
  }
  return buff;
}

int main () {
  HANDLE ipHandle = GetStdHandle(STD_INPUT_HANDLE);

  char* buffer = getInput();
  // use buff
}

You can then use your preferred multithreading API to run getInput() in a thread while having a Timer() thread with a global flag that will interrupt and end the input when time is up, getInput() is taking input.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文