【问题标题】:Repeat until user presses enter重复直到用户按下回车
【发布时间】:2019-11-06 15:24:53
【问题描述】:

我想要一个循环,直到用户按下回车键。

我尝试过使用while(getchar != '\n'){},但是这个服务员每次都输入一个。现在我不知道该怎么做。

do {
        clear;//system("cls");
        printf("\nPress [enter] to continue");
        printf(".");
        Sleep(500);
        printf(".");//should give a output with press enter to continue... and wait after every point.
        Sleep(500);
        printf(".");
        Sleep(500);
    }while(getchar() != '\n');

【问题讨论】:

  • stdin 通常是行缓冲的。在输入'\n' 之前,getchar() 可以使用 Nothing - 即使是第一次调用。也许是一个非标准函数?
  • 只有 getchar() 部分需要在循环中。

标签: c while-loop getchar


【解决方案1】:

以下代码来自kbhit for linux

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>

int kbhit(void)
{
  struct termios oldt, newt;
  int ch;
  int oldf;

  tcgetattr(STDIN_FILENO, &oldt);
  newt = oldt;
  newt.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &newt);
  oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
  fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

  ch = getchar();

  tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
  fcntl(STDIN_FILENO, F_SETFL, oldf);

  if(ch != EOF)
  {
    ungetc(ch, stdin);
    return 1;
  }

  return 0;
}

int main(void)
{
  while(!kbhit())
    puts("Press a key!");
  printf("You pressed '%c'!\n", getchar());
  return 0;
}

【讨论】:

    猜你喜欢
    • 2015-09-23
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 2019-06-13
    • 2011-12-31
    • 1970-01-01
    相关资源
    最近更新 更多