Stream makes function run forever [closed]
What kind of stream can cause to function run forever ?
Is such stream exist ?
The standard input.
ifstream("/dev/random") ifstream("/dev/zero")
If a stream encounters an error, it will stop returning/accepting information. If your function is waiting for something to come out of the stream, it will spin forever.
Use if ( cin )
(cast the stream to bool
) to test for an error condition. Alternately, call cin.exceptions( ios::badbit )
at program or stream initialization so an error condition throws an exception rather than quietly spinning.
Call cin.clear()
(or whatever stream) followed by cin.ignore()
such as to remove the offending input, if the program is able to recover from such an error.
精彩评论