Search code examples
c++menuifstream

ifstream won't open file after selecting menu choice


So my main code is a menu.

BankAccount BA;
ifstream fin;
int UserAction = -1;

while (UserAction != 0) {
    cout << "menu here";
    cin >> UserAction;

    if (UserAction == 1)
        BA.getInstance(BA); //Input by keyboard. Works fine.
    if (UserAction == 2)
        BA.getInstance(BA, fin); //Input by file.
}

If I were to choose option #2, it would execute this code:

void BankAccount::getInstance(BankAccount &BA, ifstream &fin) {
    string actN, fname, lname, InputFileName;
    double bal;

    fin.sync();
    cout << "Please enter input file path: ";
    getline(cin, InputFileName);
    if (fin.fail())
        cout << "failed";
    else {
        fin.open(InputFileName.c_str());
        BA.getInstance(BA, fin);
    }

    fin >> actN;
    fin >> lname;
    fin >> fname;
    fin >> bal;
    BA = BankAccount(actN, lname, fname, bal);
}

After entering the file path, and pressing enter, it would say failed and kick me to menu. If I put cin.sync(); where fin.sync is, it would just keep looping me to enter in the file path. Note that it works outside the menu though. How would I fix it so that it would open the file path correctly without issues so it could process the information?


Solution

  • 1 - change your main code to do-while, idk why people opt for while loops in such scenarios.

    do{
        cout << "menu here";
        cin >> UserAction;
    
        if (UserAction == 1)
            BA.getInstance(BA); //Input by keyboard. Works fine.
        if (UserAction == 2)
            BA.getInstance(BA, fin); //Input by file. 
    } while(UserAction!=0);
    

    2 - fin.fails because it isn't initialized, remove that line and it will work fine. try to use fin.fail() after fin.open();