While it is possible to do what you suggest (although you may need to clear the stream error flags if the extraction failed), it is not very elegant. In C ++, you should be able to create new objects when you need them, and discard them when you are done. Perhaps a more systematic way of writing this code is in the local loop area:
int result; while (true) { std::ifstream infile(get_random_file_name()); if (infile >> n) { break; }
You can, of course, replace the loop logic with something else that is more suitable for your situation. For example, according to the Zero-One-Many rule, you might have a container somewhere containing your candidate file names; or you can iterate over command line arguments.
Kerrek SB
source share