gpt4 book ai didi

c - 这个C代码有问题

转载 作者:太空宇宙 更新时间:2023-11-04 05:14:56 24 4
gpt4 key购买 nike

我在网站上看到过这段代码,发布这段代码的用户想知道此代码中 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com