c - 如果没有什么可读的,如何跳过 getchar()?

标签 c getchar

我编写了一个简单的交互式程序,它需要用户输入。 读取特定输入后,它会采取特定操作,但首先会通过从流中读取任何剩余字符来检查用户是否输入了太多命令。

我的问题是:如果流中没有剩余字符,它就会卡住,直到用户按下回车键。有没有办法覆盖它?

这是检查输入流中剩余字符的函数:

int check_end_of_stream(void){
    char c;
    c=getchar();
    for(; c!='\n' && c!=EOF; c=getchar())
        if(c!=' ' || c!=','){
            printf("You have written too many statements");
            printf(" in your command line!\n");
            return 0;
        }
    return 1;
}

提前致谢!

附言我在 Linux 中编程

最佳答案

另一种解决方案是使用 getche() 方法,它不会等待按下回车...

int check_end_of_stream(void){
char c;

for(c=getche(); c!='\n' && c!=EOF; c=getche())
if(c!=' ' || c!=','){
    printf("You have written too many statements");
    printf(" in your command line!\n");
    return 0;
}
return 1; 
}

关于c - 如果没有什么可读的,如何跳过 getchar()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16494333/

相关文章:

c - Strncmp:异常段错误

c - 套接字编程中从客户端获取char()

c - K&R 练习 1-9 C 编程解决方案

C 堆栈分配的字符串作用域

c - 简单的互斥应用程序无法正常工作?

c - 用于循环速度 c 的英特尔编译器

c - C : why it won't print a character right after I use getchar? 中的 getchar() 函数

c - Haskell 外来类型的惯用用法?

c - 添加 32 位有符号 C

c - 在 C 中每次循环迭代读取三个字符?