【问题标题】:forcing the buffer to clear in scanf强制缓冲区在 scanf 中清除
【发布时间】:2019-11-16 22:07:26
【问题描述】:

我的程序中的 scanf 和输入缓冲区有问题。

首先我要求用户输入:

char someVariable;
printf("Enter text: ");
scanf(" %c",&someVariable);

然后我有一个循环,在 scanf 中一次遍历一个字符,直到它到达 \n。 问题是循环完成后,不知何故,缓冲区中仍有一些东西,所以这个函数(在循环中被调用)再次被调用并破坏了我程序中的逻辑。

如何强制清除输入缓冲区?

我只能使用scanf(作业要求)

void checkType(){
    char userInput;
    char tempCheckInput;
    printf("Enter Text: ");
    scanf(" %c",&userInput);
    while (userInput != '\n'){

        tempCheckInput = userInput;
        scanf("%c",&userInput);

忽略循环的结尾,这是我得到输入的部分

【问题讨论】:

  • 向我们展示代码,请参阅minimal reproducible example。
  • @user3386109 这是一个很长的程序,所以我不想复制超过 100 行,我会在一秒钟内编辑帖子

标签: c scanf input-buffer


【解决方案1】:

如何强制清除输入缓冲区?

在 C 中,像 stdin 这样的 流 不能被清除(以标准方式),如“在 时间 内删除到目前为止的所有输入” .

相反,输入可以消耗和折腾(类似于“清除”)输入直到数据条件。

通常的方式是

int consume_rest_of_line(void) {
  int ch;
  while ((ch = getchar()) != '\n' && ch != EOF) {
    ;
  }
}

如果限于scanf()

int consume_rest_of_line(void) {
  char ch;
  while (scanf("%c", &ch) == 1 && ch != '\n') {
    ;
  }
}

【讨论】:

    猜你喜欢
    • 2012-11-19
    • 2011-04-15
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    相关资源
    最近更新 更多