コメントを見つけましたこれiostream::eof
ループ条件で使用するのは「ほぼ間違いなく間違っている」という回答。私は通常、次のようなものを使用しますwhile(cin>>n)
。これは暗黙的に EOF をチェックすると思います。
明示的に eof をチェックするのはなぜwhile (!cin.eof())
間違っているのでしょうか?
scanf("...",...)!=EOF
C で使用する場合 (問題なくよく使用します)とどう違うのでしょうか?
ベストアンサー1
ストリームの末尾を読み取った後にiostream::eof
のみ返されるからです。次の読み取りがストリームの末尾になることを示しているわけではありません。true
次のことを考慮してください (次の読み取りはストリームの最後になると仮定します)。
while(!inStream.eof()){
int data;
// yay, not end of stream yet, now read ...
inStream >> data;
// oh crap, now we read the end and *only* now the eof bit will be set (as well as the fail bit)
// do stuff with (now uninitialized) data
}
これに対して:
int data;
while(inStream >> data){
// when we land here, we can be sure that the read was successful.
// if it wasn't, the returned stream from operator>> would be converted to false
// and the loop wouldn't even be entered
// do stuff with correctly initialized data (hopefully)
}
2つ目の質問ですが、
if(scanf("...",...)!=EOF)
と同じです
if(!(inStream >> data).eof())
同じではない
if(!inStream.eof())
inFile >> data