如何在不输入值的情况下终止 scanf()

  • 本文关键字:终止 情况下 scanf c
  • 更新时间 :
  • 英文 :

#include "stdio.h"
main()
{
    int option;
    printf("Enter the value :");
    scanf("%d",&option);
    printf("Your value is %dn",option);
}

这是我的简单 C 程序,用于从用户那里获取值并打印出来。我有一个疑问为什么 scanf 会等到输入值,当 即按回车键时它不会终止。

例如:

16:26:40-$./a.out
  Enter the value: <-|
<-|
<-|
<-|
<-|
<-|
<-|
   1
Your value is 1

我需要清晰的概念,解决方案是什么?

提前致谢

scanf 的工作原理:

对于格式字符串中的每个转换说明符 scanf ,它会尝试在输入中查找适当类型的项目,必要时跳过空格。然后,它会读取该项,并在遇到不属于数据项的字符时停止。

在以下情况下

scanf("%d",&option);  

optionint数据类型。 scanf搜索数字的开头并忽略空格字符(换行符、空格、制表符等(,这就是它等到输入整数的原因。

你是对的.. scanf并不总是好的。我会做这样的事情:

#include "stdio.h"
void main( void )
{
    int option;
    int res;
    char buff[20];
    printf("Enter the value :");
    gets(buff);
    res = sscanf(buff,"%d",&option);
    if(res == 1)
        printf("Your value is %dn",option);
}

gets 在换行符处终止并将字符串存储在 buff 中。sscanf读起来像scanf(格式相同(,但来自C字符串输入而不是stdin。

sscanf(以及 scanf(返回参数列表中成功填充的项目数,如果它无法读取任何内容,则返回 EOF。 由于我们只填写 1 个项目,因此我们检查: if(res == 1) .

也许有一些更好的方法来做到这一点,但我认为这类似于您的代码,因此在需要时更改代码可能更容易。

Ted 是如何提到的,'fclose(stdin(;'对我来说也很好用。

在"主要"处,我补充说:

if (signal(SIGINT, handler_SIGINT) == SIG_ERR) {
  printf("Fail capture SIGINTn");
}

签名处理程序 :

static void handler_SIGINT(int sig) {
  printf("CTRL+Cn");
  fclose(stdin);
}

如果你在SIGINT处理程序中放一个fclose(stdin(会怎样?对我有用,但可能不是最佳实践:

void quitproc(int in)
{
    printf("Got the Ctrl-Cn");
    ExitLoop = 1;
    // This will exit scanf
    fclose(stdin);
}

相关内容

最新更新