为什么fflush(..)不适用于c2和c0
如果我使用c0 = 0和c2 = 0声明,它可以工作,但fflush(stdin)不工作,我试着放在不同的地方,但它不工作,我使用ubuntu13.04中的代码块;
int main(void)
{
int cod ,passou = 0, c0, c1, c2, c3, ct;
float p1, p2, p3;
char o;
do {
puts ("Informe codigo: ");
scanf ("%i", &cod);
fflush (stdin);
switch (cod)
{
case 0:
c0 = c0 + 1;
break;
case 1:
c1 = c1 + 1;
ct = ct + 1;
break;
case 2:
c2 = c2 + 1;
ct = ct + 1;
break;
case 3:
c3 = c3 + 1;
ct = ct + 1;
break;
default:
puts ("Valor invalido");
}
getchar();
puts ("Deseja informar mais um voto?");
fflush (stdin);
scanf("%c",&o);
if (o == 'S' || o == 's' ) {
passou = 0;
} else if (o == 'N' || o == 'n' ) {
passou = 1;
} else {
puts ("Opcao invalida");
}
} while ( passou != 1 );
p1=(c1/ct)*100;
p2=(c2/ct)*100;
p3=(c3/ct)*100;
if (c1 > c2 && c1 > c3 && c1 > c0 ) {
puts ("Candidato numero 1 eh o vencedor");
} else if (c2 > c1 && c2 > c3 && c3 > c0) {
puts ("Candidato numero 2 eh o vencedor");
} else if (c3 > c1 && c3 > c2 && c3 > c0) {
puts ("Candidato numero 3 eh o vencedor");
} else {
puts ("Numero de votos em branco eh maior do que todos os outros candidatos");
}
printf ("\nTotal de votos do candidato 1: %d", c1);
printf ("\nTotal de votos do candidato 2: %d", c2);
printf ("\nTotal de votos do candidato 3: %d", c3);
printf ("\nTotal de votos em branco: %d", c0);
printf ("\nPercentual de votos do candidato 1: %.2f", p1);
printf ("\nPercentual de votos do candidato 2: %.2f", p2);
printf ("\nPercentual de votos do candidato 3: %.2f", p3);
return 1;
}发布于 2013-05-26 02:43:22
fflush(stdin)未定义此behavior.Use,以便在使用scanf()时处理保留在stdin缓冲区中的换行符,特别是在需要读取字符但缓冲区中剩余的换行符被自动用作字符的情况下:
while((c = getchar()) != '\n' && c != EOF);以下是cplusplusreference对fflush()的评论(你也可以从其他来源证实这一点,因为这里有太多的老兵对cplusplusreference不屑一顾,尽管他们没有完全谴责它)
......In some implementations, flushing a stream open for reading causes its input buffer to be cleared (but this is not portable expected behavior).....
http://www.cplusplus.com/reference/cstdio/fflush/
发布于 2013-05-26 02:40:41
在你的系统中,ubuntu13.04 (Unix或Linux)调用fflush (stdin);是未定义的行为!
int fflush(FILE *ostream);
ostream指向未输入最新操作的输出流或更新流,则fflush函数会导致要传送到主机环境的该流的任何未写入数据都将写入文件;否则,行为是未定义的
要学习正确刷新输入缓冲区的技巧,可以使用以下一些代码片段,这些代码片段实际读取并丢弃输入缓冲区中不需要的字符。在读取实际数据之前,您可以将其用作fflush。
对于C:
while ((ch = getchar()) != '\n' && ch != EOF); 对于C++
while ((ch = cin.get()) != '\n' && ch != EOF);但是,如果在输入流中没有数据时调用这些函数,程序将一直等到有数据时才调用,这会给您带来不希望看到的结果。
阅读:@Keith Thompson的答案:"Alternative to C library-function fflush(stdin)"
编辑:
有些平台完全定义了fflush(stdin) (作为该平台上的非标准扩展)。主要的例子是一个众所周知的系统系列,统称为Windows。微软的规范:
Flushes a stream
int fflush(FILE *stream )函数用于刷新流。如果与流关联的文件已打开以供输出,则fflush会将与流关联的缓冲区的内容写入该文件。如果流是为ungetc input**,**打开的,则fflush 将清除缓冲区的内容。 fflush将取消对流的任何先前调用ungetc的效果。此外,fflush(NULL)还会刷新所有打开以进行输出的流。在调用之后,流保持打开状态。fflush对未缓冲的流没有影响。
https://stackoverflow.com/questions/16752759
复制相似问题