首页 > 解决方案 > 在循环中一起使用 printf 和 fgets

问题描述

我正在尝试实现一个简单的程序,它可以无限地读取用户的输入,然后打印出来。但也有一些问题。这是一个简单的问题,但我的谷歌搜索并没有为我提供任何解决方案。这是代码。

int main() {

    char pass[32];
    int x=10;

    while (x!=0) {


        printf("\nInput the password: ");
        fgets(pass, sizeof(pass), stdin);

        printf("that is what i read: %s", pass);
    }
    return 0;
}

当我输入一个超过 32 个字符的字符串时,它的行为异常。

Input the password: pass
that is what i read: pass

Input the password: passsssss
that is what i read: passsssss

Input the password: passssssssssssssssssssssssssssssss
that is what i read: passsssssssssssssssssssssssssss
Input the password: that is what i read: sss

Input the password:

您在第三次尝试中看到,它会自动打印第三行。我没有输入“这就是我读到的内容:sss”。

为什么会这样?

标签: c

解决方案


fgets()不限制用户输入的行的长度。 fgets()限制读取该行的多少。

输入过多,剩余部分留给下一个输入操作。


如果输入 viafgets()缺少 a '\n',则要么

  • 整行没有读完,(很常见)
  • 输入 w/o'\n'然后结束文件,(很少)
  • 读取了一个空字符。(稀有的)
  • 输入缓冲区小于 1。(病态)

下面很容易识别前 2 个。

// Test if anything was read.
if (fgets(pass, sizeof pass, stdin)) {
  // Was it missing a '\n'?
  if (strchr(pass, '\n') == NULL) {
    // Read rest of line and throw it away
    int ch;
    while ((ch = fgetc(stdin)) != '\n' && ch != EOF) {
      ;
    }
  }
}

推荐阅读