【问题标题】:Using getchar() to exit a loop when user hits 'Enter'?当用户点击“Enter”时使用 getchar() 退出循环?
【发布时间】:2014-03-20 00:25:11
【问题描述】:

我已经阅读了很多关于此的其他堆栈溢出主题,但我仍然遇到很多麻烦。我尝试使用 do/while 循环以及嵌套的 if 语句。当“玩家”点击“进入”时,如果停止打印“卡片”,我无法获得最后一个。以太 getchar() 支持 if 语句,因此只有在用户连续按 Enter 键时才会打印(这甚至不接近我的意图),或者它只是在暂停后继续打印。

void printDeck(Card *deck, const char *faces[], const char *suits[], FILE *fp)
{
    int loop, t;
    // print the deck one card at a time

    fp = fopen("cardsprinted.txt", "w+");
    t = ftell(fp);
    char c;
    do {
        c = getchar();    
        for (loop = 0; loop < 52; loop++) {
            // print the face and suit of the card to stdout as well as file
            printf("%s of %s\n",faces[deck[loop].face],suits[deck[loop].suit]);
            fprintf(fp,"%s of %s\n",faces[deck[loop].face],suits[deck[loop].suit]);
            fseek(fp, t, SEEK_SET); // finds beginning of the file
            fseek(fp,t,SEEK_END);// finds end of file for printing

            // loop to pause for 3seconds before printing next card. 
            if ((loop % 1) == 0 && loop != 0) { 
                sleep(3);
            }
        }
    } while (c != '\n' && c != EOF);

    fclose(fp);
}

输出示例:

./slapjack
Queen of Spades
Nine of Spades
Jack of Hearts

这是我按 Enter 并希望循环停止打印的地方。

Three of Hearts
Queen of Hearts
Six of Spades
Seven of Diamonds
^C

但它不起作用......

我也试过不使用 getchar()。我想也许 scanf() 会更容易,但仍然没有运气。

【问题讨论】:

  • c 应该是 int,而不是 char。这是因为EOF 必须(并且)不同于getchar() 可以返回的任何值,因此您需要比char 提供的更多位存储空间。
  • 如果您的意思是您希望某人能够“实时”按下您可以检测到的按键,但如果他们不按键,程序必须继续运行 - 那不是可能使用标准 C,您将必须进行操作系统调用,或使用诸如 ncurses 之类的库,它可以在不输入整行的情况下读取键盘。
  • 您需要将STDIN 置于非阻塞模式,或生成pthread 以阻塞stdin,并提供一个信号量,您将尝试在循环中获取该信号量。

标签: c loops if-statement do-while


【解决方案1】:

使用 while 语句。

将控制变量设置为 true

进入前,测试getchar是否检测到set control var为false

进入while循环

下面的伪代码:

controlvar = ! getchar()

while (controlvar) {
  do something
  test for end condition or getchar to set controlvar false
}

【讨论】:

    猜你喜欢
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多