fflush不起作用

为什么fflush(..)c2c0不起作用?
如果我使用声明c0 = 0c2 = 0它可以工作,但fflush(stdin)不起作用,我试图放在不同的地方,但它不起作用,我使用ubuntu 13.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; } 

fflush(stdin)具有未定义的行为。使用此函数来处理使用scanf()时保留在stdin缓冲区中的换行符,尤其是当您需要读取一个字符但缓冲区中剩余的换行符被自动占用时人物 :

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

以下是关于fflush()cplusplusreference所说的内容(你也可以从其他来源validation相同的内容,因为这里有太多的退伍军人对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/

在你的系统ubuntu 13.04(Unix或Linux)上调用fflush (stdin); 是未定义的行为!

int fflush(FILE *ostream);

ostream指向输入流或未输入最近操作的更新流,fflush函数导致该流的任何未写入数据被传递到主机环境以写入文件; 否则,行为未定义

要学习正确刷新输入缓冲区的技巧,您可以使用以下一些实际读取的代码片段并从输入缓冲区中丢弃不需要的字符。 在读取实际数据之前,您可以将其用作fflush。 阅读此FAQ条目。

对于C

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

对于C ++

  while ((ch = cin.get()) != '\n' && ch != EOF); 

但是,如果在输入流中没有数据时调用它们,程序将等到存在,这会给您带来不良后果。

阅读:@ Keith Thompson的回答: “替代C库函数fflush(stdin)

编辑:
有些平台完全定义了fflush(stdin) (作为该平台上的非标准扩展)。 主要的例子是一个众所周知的系统系统,统称为Windows。 微软的规格:

刷新流

int fflush(FILE *stream )函数刷新流。 如果与stream关联的文件打开以进行输出,则fflush会向该文件写入与该流关联的缓冲区的内容。 如果流打开inputfflush清除缓冲区的内容。 fflush否定任何先前调用ungetc对流的影响。 此外, fflush(NULL)刷新为输出打开的所有流。 电话会议后,电话会保持打开状态。 fflush对无缓冲的流没有影响。