需要循环要求用户重新输入文件名,直到更正

时间:2016-10-21 14:54:39

标签: c++ loops while-loop

如果用户输入错误的文件名,我怎么能修复循环以要求用户反复重新输入文件名?

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;
}

2 个答案:

答案 0 :(得分:0)

也许这个:

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;


}

答案 1 :(得分:0)

我不认为你做的while循环可以做你想做的事。

分号后循环结束,因此循环中的块不会在循环中执行。

我认为您正在寻找的是这样的:

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";
    }
} while (in_stream.fail());