Logan Logan - 1 month ago 18
C++ Question

Need loop to ask user to re enter the file name until correct

How am I able to fix the loop to ask the user to retype the filename over and over again if they type in the wrong file name?

using namespace std;

void get_input_file(ifstream &in_stream);

int main()
{
ifstream in_stream;

cout << "Welcome to the Test Grader." << endl;
get_input_file(in_stream);
}

void get_input_file(ifstream &in_stream) {
string file_name;

do {
cout << "Enter the file name you would like to import the data from: " << endl;
cin >> file_name;

in_stream.open(file_name.c_str()); //Opens the input file into the stream}
}

while (in_stream.fail()); {
cout << "Error finding file, try again.\n";
}

cout << "Testing: " << endl;
cout << file_name << endl;


}

Answer

maybe this:

using namespace std;

void get_input_file(ifstream &in_stream);

int main()
{
    ifstream in_stream;

    cout << "Welcome to the Test Grader." << endl;
    get_input_file(in_stream);
}

void get_input_file(ifstream &in_stream)
{
    string file_name;

    do
    {
        cout << "Enter the file name you would like to import the data from: " << endl;
        cin >> file_name;

        in_stream.open(file_name.c_str());  //Opens the input file into the stream
        if(in_stream.fail())
        {
            cout << "Error finding file, try again.\n";
            continue;
        }
        break;
    } while(true);


    cout << "Testing: " << endl;
    cout << file_name << endl;


}