?
Solved

C++ question - using ifstream

Posted on 2001-06-09
1
Medium Priority
?
1,098 Views
Last Modified: 2012-08-14
If I use this statement:

cout<<"File Name >";
cin>>filename;
ifstream input("filename.dat", ios::nocreate);

and the user inputs a file name that doesn't exist
is there a way to allow the user to enter the name again? The program halts if the file name is incorrect.  I have tried putting this in a loop, but it seems like the program fails so it halts.  Do I have to use exception handling?
0
Comment
Question by:fmora060901
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 8

Accepted Solution

by:
mnashadka earned 150 total points
ID: 6172606
Try something like:

ifstream input;

while(true)
{
  cout << "File Name >";
  cin >> filename;
  input.clear(); // Clear the last failure flags
  input.open(filename, ios::nocreate);
  if(! input)
    cout << "There was an error opening that file";
  else
    break;
}
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.
Suggested Courses

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question