【问题标题】:How to skip getchar() if there is nothing to read?如果没有可阅读的内容,如何跳过 getchar()?
【发布时间】:2013-05-11 06:06:40
【问题描述】:

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

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

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

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 中编程

【问题讨论】:

  • 你需要超时机制,用read()代替getchar()
  • 阅读:getchar() non-blocking 将帮助您
  • 有办法做到这一点,但没有标准的办法做到这一点。 Unix 上的方式与 Windows 上的方式不同,因此您至少应该指定要在其上工作的系统。对于 Unix,您可能会查看 curses 库,或查看非阻塞 I/O 选项,并且可能还有其他一些技术,例如超时。

标签: c getchar


【解决方案1】:

另一种解决方案是使用 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; 
}

【讨论】:

  • getche() 来自哪个库?
  • 请注意getchar() 和亲戚返回int 而不是char。这是因为它们必须能够返回任何有效的char 值加上一个不同的值 EOF。使用char 而不是int 会导致两个问题之一。如果普通 char 是有符号类型,则某些有效字符(通常是 ÿ、y-umlaute、0xFF、U+00FF、带分音符号的拉丁小写字母 Y)会被错误识别为 EFO。如果plain char 是无符号类型,则分配给char 变量的值永远不会被识别为EOF。两者都不是真的可以接受。
猜你喜欢
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-06
相关资源
最近更新 更多