首页 > 解决方案 > 是否有防止用户在功能运行时输入的功能?

问题描述

我制作了一个功能之间有延迟的程序,当程序运行时,用户可以在程序运行时干扰和输入字符。

该程序一次打印一个字符串的字符,延迟为 0.1 秒,但是在打印字符串时,用户可以通过输入和在字母之间进行干扰。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


void delay(unsigned int milliseconds){
    clock_t start = clock();
    while((clock() - start) * 1000 / CLOCKS_PER_SEC < milliseconds);
    }

void text (int br, char sentence []){
    int c = 0;
    for (c = 0; c < br; c++){
        printf("%c", sentence[c]);
        fflush(stdout);
        delay (100);
        }
    }

int main(){
text (15,"Hello friends!\n");
}

我希望看到文本被打印出来,而不会在延迟之间产生任何干扰。

标签: c

解决方案


这是不可能以便携式方式完成的。如果您使用的是 Linux,则可以查看ncurses库。

如果您对禁用输出感到满意并且在 POSIX 系统上,您可以这样做:

void text (int br, char sentence []){
    system("stty -echo");

    /* Your previous code */

    system("stty echo");
}

如果您还想从该函数运行时键入的任何内容中清除标准输入:

void text (int br, char sentence []){
    system("stty -echo");

    /* Your previous code */

    int ch; while ((ch = getchar()) != '\n' && ch != EOF);        
    system("stty echo");
}

光标可以用system("setterm -cursor off");


推荐阅读