fflush関数はどんな役割を果たしますか?
说明:ある友达は本文のプログラムの结果に対して疑问を出して、だからここで言って、私はWindows VC++6.0の上でテストしたので、プラットフォームと环境の违いに注意してください.
まず簡単な単語を復習しましょう.
flush(fが1つしかないことに注意):洗浄、洗浄、洗浄.例文:I flushed the toilet and went back to work again.
次に、簡単な関数を見てみましょう.fflush(file flush、注意は2つのfがあります)、まず簡単なプログラムを見てみましょう.
このプログラムを実行し、1を入力してenterキーを押すと、次のようになります.
49 10
驚くことなく、この結果は正常で、文字1に対応するASCII値はちょうど49で、enterキーに対応するASCII値は10なので、このような結果になりますね.2番目のscanf関数が実行され、バッファから値が得られたことがわかります(実は、この値は私たちが望んでいるものではありません).では、バッファという「便器」の中の値をどのように流すのでしょうか.fflush関数でいいです.以下のようにします.
これで、10は表示されません.
次に、MSDN(2008)の一例を見てみましょう(MSDNで与えられたプログラムはもちろん正しいでしょう):
その邪を信じないなら、上のプログラムのfflushの行を注釈して、プログラムを実行して、あなたはどんな結果があるか知っています.したがって、fflushの役割もわかります.
最後に、MSDNの話を見て、本稿を終了します.
fflush has no effect on an unbuffered stream.
Buffers are normally maintained by the operating system, which determines the optimal time to write the data automatically to disk: when a buffer is full, when a stream is closed, or when a program terminates normally without closing the stream.
まず簡単な単語を復習しましょう.
flush(fが1つしかないことに注意):洗浄、洗浄、洗浄.例文:I flushed the toilet and went back to work again.
次に、簡単な関数を見てみましょう.fflush(file flush、注意は2つのfがあります)、まず簡単なプログラムを見てみましょう.
#include
int main()
{
char c;
scanf("%c", &c);
printf("%d
", c);
scanf("%c", &c);
printf("%d
", c);
return 0;
}
このプログラムを実行し、1を入力してenterキーを押すと、次のようになります.
49 10
驚くことなく、この結果は正常で、文字1に対応するASCII値はちょうど49で、enterキーに対応するASCII値は10なので、このような結果になりますね.2番目のscanf関数が実行され、バッファから値が得られたことがわかります(実は、この値は私たちが望んでいるものではありません).では、バッファという「便器」の中の値をどのように流すのでしょうか.fflush関数でいいです.以下のようにします.
#include
int main()
{
char c;
scanf("%c", &c);
printf("%d
", c);
fflush(stdin); // “ ”
scanf("%c", &c);
printf("%d
", c);
return 0;
}
これで、10は表示されません.
次に、MSDN(2008)の一例を見てみましょう(MSDNで与えられたプログラムはもちろん正しいでしょう):
#include
#include
void main( void )
{
int integer;
char string[81];
/* Read each word as a string. */
printf( "Enter a sentence of four words with scanf: " );
for( integer = 0; integer < 4; integer++ )
{
scanf( "%s", string );
printf( "%s
", string );
}
/* You must flush the input buffer before using gets. */
fflush( stdin );
printf( "Enter the same sentence with gets: " );
gets( string );
printf( "%s
", string );
}
その邪を信じないなら、上のプログラムのfflushの行を注釈して、プログラムを実行して、あなたはどんな結果があるか知っています.したがって、fflushの役割もわかります.
最後に、MSDNの話を見て、本稿を終了します.
fflush has no effect on an unbuffered stream.
Buffers are normally maintained by the operating system, which determines the optimal time to write the data automatically to disk: when a buffer is full, when a stream is closed, or when a program terminates normally without closing the stream.