【问题标题】:Use "while" to check if there is a blank line C使用“while”检查是否有空行 C
【发布时间】:2025-11-29 23:35:01
【问题描述】:

代码是检查是否有空行。我想当我输入一些文本时,它会继续执行 printf(),因为它卡在循环中。但实际上,它只是执行 printf() 一次,然后等待另一行文本。为什么?是不是因为gets()函数后输入会被擦除?

这里是代码

int main(){
    char input[257];
    char *ptr;

    puts("Enter text a line at a time, then press Enter");
    puts("Enter a blank line when done");

    while( *(ptr= gets(input)) != NULL){
        printf("You've entered: %s\n", input);
    }
    puts("Thank you and goodbye\n");

    return 0;
}

【问题讨论】:

  • 运行条件,如果为真则再次运行主体和条件,如果为真则再次运行主体和条件,然后...
  • @Ashiquzzaman 谢谢,我明白了。如果重写输入,一切都会有意义。
  • 仅供参考。 get 的手册页在 BUGS 部分中说明了这一点,永远不要使用 gets()。因为事先不知道数据是不可能知道gets()会读取多少个字符的,所以……一定要读
  • *(ptr= gets(input)) != NULL 应该是 *(ptr= gets(input)) != 0,因为 *(ptr= gets(input)) 的类型是 char 而不是 char*。除此之外,您的程序可以正常运行,因为每次在您的 while 循环开始时都会评估 *(ptr= gets(input)) != 0
  • gets 是不安全的,因为它很容易超出输入缓冲区。而不是gets(input) 使用fgets(input, 257, stdin)fgets(input, sizeof(input), stdin)。 (只有input 是数组而不是指针时,才应使用带有sizeof(input) 的形式。)

标签: c while-loop gets puts


【解决方案1】:

这个时候应该可以解决问题

while( (ptr= gets(input)) != NULL && input[0]!='\0')

【讨论】: