Solved

C++ question - using ifstream

Posted on 2001-06-09
1
1,077 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
1 Comment
 
LVL 8

Accepted Solution

by:
mnashadka earned 50 total points
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

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…
Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

772 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now