c - 这个C代码有问题

标签 c

我在网站上看到过这段代码,发布这段代码的用户想知道 此代码中 fflush(stdin) 的影响。这是下面的代码

main()
{
  char *str1="string one";
  char *str2="string two";
  char charbuf; // store characters in buffer

  puts("\nEnter first string");
  gets(str1);
  fflush(stdin);  /*what does this mean here*/

  while( (charbuf=getchar() ) != EOF && charbuf!='\n')
      ; // clear unwanted data

  puts("\nEnter second string");
  gets(str2);
  fflush(stdin);/*what does this mean here*/

  while( (charbuf=getchar() ) != EOF && charbuf!='\n')
      ;

  for(;*str1==*str2&(*str1!='\0'||*str2!='\0\);str1++,str2++) ;
  {
    printf("\nthe string are equal");
  }
  else   
  {
   printf("\nthe string are not equal");
   }
 return;
}

但对我来说,在达到 fflush(stdin) 语句之前,程序员已经犯了一个大错误,即使用 get(str1);

这里用gets(str1)可以吗??

最佳答案

Flushing stdin is undefined by the standard因此错误。它应该执行以下 while 执行的操作:丢弃用户输入直到(包括)\n

fflush(stdin);/*what does this mean here*/

使用gets 是永远不可能的,因为fgets 始终可用并且gets 将从the next version of the standard 中删除.

Removal of the gets function, deprecated in the current C language standard revision, ISO/IEC 9899:1999/Cor.3:2007(E), in favor of a new safe alternative, gets_s

编辑

很明显,因为 str1str2 指向字符串文字,所以它们是不可写的。写入它们(通过 gets 或其他任何方式)是未定义的。

关于c - 这个C代码有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7241778/

相关文章:

c - 我的链表实现有什么问题?

c - 相同的指针在不同的编译器中显示不同的大小

c - 我想用字符串填充二维指针数组

c - 在不使用字符串库函数的情况下替换 C 中的子字符串

c - 将整数与C中指针数组的元素相乘

c - 在 C 程序中使用 glib 库

c - Linux下C语言包生成率测量

c - 内存中的套接字文件描述符是什么形式?

c - 在 C 中为用户输入添加下划线

c - 我的程序不接受 scanf 命令的输入