当它仅读取换行符时,gets()会保存什么

问题描述 投票:2回答:2

这是Prata的C Primer Plus]中对gets()的描述:]

通常从系统的标准输入设备获取一个字符串您的键盘。由于字符串没有预定长度,因此gets()需要一种知道何时停止的方法。它的方法是读取字符直到到达换行符(\n)为止,按Enter键。最多要包含所有字符(但不是包括)换行符,添加一个空字符(\0)并给出调用程序的字符串。

我很好奇gets()仅读换行符会发生什么。所以我写了这个:

  int main(void)
  {
    char input[100];

    while(gets(input))
    {
      printf("This is the input as a string: %s\n", input);
      printf("Is it the string end character? %d\n", input == '\0');
      printf("Is it a newline string? %d\n", input == "\n");
      printf("Is it the empty string? %d\n", input == "");
    }

    return 0;
  }

这是我与程序的互动:

$ ./a.out
This is some string
This is the input as a string: This is some string
Is it the string end character? 0
Is it a newline string? 0
Is it the empty string? 0

This is the input as a string:
Is it the string end character? 0
Is it a newline string? 0
Is it the empty string? 0

第二个输入框实际上是我感兴趣的东西,当我按下所有输入键时。在这种情况下,input到底是什么?这似乎不是我的任何猜测:\0\n""

这是Prata的C Primer Plus中的gets()的描述:它从系统的标准输入设备(通常是键盘)中获取字符串。因为字符串没有预定的长度,所以gets()...

c stdin gets
2个回答
2
投票

gets的描述中的这一部分可能令人困惑:


3
投票

将字符串设置为fgets,即""。不过,请不要使用{'\0'}。它会导致缓冲区溢出。

© www.soinside.com 2019 - 2024. All rights reserved.