Quick Help :)

Would this be good if I wanted to verify a file a user gave me was correct?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
ifstream readSalesFile;
readSalesFile.open(SalesFile);

 //validate if the sales file open
    if(!readSalesFile)
        {
            while(true)
                {cout<<" Enter path to your sales file: \n";
                getline (cin,SalesFile);

                readSalesFile.open(SalesFile);
                    if (readSalesFile)
                    {
                        continue;
                    }
                }
        }

    else
        {
            cout<<"Your File Opened!.";
        }
You have an infinite loop here.

What do you want to do? Check if file exist and can be opened?
yes @MiiNiPaa

I think I should change line 14 continue to break.

But I don't know if my logic is correct.
Last edited on
Well, underlying logic is correct: if file stream is opened and is not in error state, then file does exist and avaliable to us.

Although "Your File Opened!." string would be shown only if file was opened succesfully first time at line 2.
what would u recommend if I wanted to get out of loop and continue with program?

Is their anything that I can do besides get statement?
Last edited on
You do not need to place "FIle opened" message in else branch. Actually you do not need conditional branching at all. Consider this:

1
2
3
4
5
6
7
8
9
10
11
12
//Default-construct our file stream
//so it is no associate with any file yet.
std::ifstream readSalesFile; 

while(not readSalesFile.is_open() ) { //Loop until we properly open file
    std::cout << "Enter path to your sales file:\n";
    std::getline(std::cin, salesFile); //get file name
    readSalesFile.open(salesFile); //Try to open it
}
//Following line will be executed only after loop finishes,
//i.e. when file was properly open
std::cout << "File was opened!\n";
ohh I was just thinking too deep into it, thanks a lot MiiNiPaa.

I guess sometimes it is more simpler than I make it out to be.
Topic archived. No new replies allowed.