使用fflush(stdin)
有什么区别
和 flushstdin()
?我知道的唯一区别是我需要在使用 flushstdin()
之前编写那些无效的东西,但我不知道为什么。
void flushstdin()
{
int c;
while((c = getchar()) != '\n' && c != EOF);
}
int main () {
float a, b, c;
float s=0, ar1=0, ar2=0;
printf("Inform value of side A");
while(scanf("%f",&a) != 1 || a <= 0){
printf("Invalid value.\n");
flushstdin();
}
}
和
int main(){
float a,b,c,s=0;
printf("Inform value of side A.");
while(scanf("%f",&a) != 1 || a<=0){
printf("Invalid value.\n");
fflush(stdin);
}
}
我是初学者!哪个代码最好?或者它们是相等的?
最佳答案
区别在于 flushstdin
是用户定义的,并且是标准 C 中刷新 stdin
的唯一方法。
fflush
是一个标准库函数。 fflush(stdin);
将调用未定义的行为。
fflush
is defined only for output streams. Since its definition of "flush" is to complete the writing of buffered characters (not to discard them), discarding unread input would not be an analogous meaning forfflush
on input streams.
There is no standard way to discard unread characters from a stdio input stream. Some vendors do implement
fflush
so thatfflush(stdin)
discards unread characters, although portable programs cannot depend on this. (Some versions of thestdio
library implementfpurge
orfabort
calls which do the same thing, but these aren't standard, either.) Note, too, that flushingstdio
input buffers is not necessarily sufficient: unread characters can also accumulate in other, OS-level input buffers. If you're trying to actively discard input (perhaps in anticipation of issuing an unexpected prompt to confirm a destructive action, for which an accidentally-typed "y" could be disastrous), you'll have to use a system-specific technique to detect the presence of typed-ahead input; see questions 19.1 and 19.2. Keep in mind that users can become frustrated if you discard input that happened to be typed too quickly.
关于c - fflush(stdin) 和 flushstdin() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30675045/