how to do a loop if the infilename is not good??

Hi,

If I was to open a file name but I typed in the incorrect one how would I write up a loop for that?
So say if the file name I wanted to open was "calex.txt" and I typed in "caelx.txt" how would I do a loop so that it would keep asking me to "open file name" until I got it correct?

Thanks in advanced!
1
2
3
4
5
6
7
8
9
10
11
12
13
ifstream fin; // assuming an input file

while ( true )
{
    cout << "Enter filename: ";
    string filename;
    getline ( cin, filename );
    if ( filename.length() == 0 ) exit ( -1 ); // or whatever

    fin.open ( filename.c_str() );
    if ( fin ) break;
    cout << "Look buddy, I don't have all day....\n";
}

1
2
3
4
5
6
7
8
9
10
11
12
13
    cout<<"Enter file name: ";
    cin>>infilename;
    
    infile.open(infilename.c_str());
       while(!infile.good())
       {
           cout<<"Enter file name: ";
           infile.close();           
           cin>>infilename; 
           infile.clear();                
           infile.open(infilename.c_str());
       }


I converted it. But once I input the right text file, it doesnt allow me to do anything else. Cause I'm supposed to have an outfile and name it.
Like

Enter file name: kitkat.txt
Enter outfile name: tommy

but it just appears like this

Enter file name: kitkat.txt
_

with a blinking cursor.
1
2
3
4
5
6
7
8
9
10
11
12
13
string filename = "";
ifstream myFile;
cout<<"Enter File name :";
cin>>filename;
myFile.open(filename.c_str);
if(myFile.is_open())
{
cout<<filename<<" is open"<<endl;
}
else
{
cout<"error"<<Endl;
}

Don't use cin>>infilename;
use getline ( cin, infilename );
everyone says that but they never explain why, do you know why that is better?
getline simply ensures that you've read (and discarded) the newline.
cin>> leaves the newline behind.
That can cause trouble.
alright thanks i see now, time to switch over
Topic archived. No new replies allowed.