#c #loops #while-loop
#c #циклы #цикл while
Вопрос:
Как я могу исправить цикл, чтобы просить пользователя повторно вводить имя файла снова и снова, если они вводят неправильное имя файла?
using namespace std;
void get_input_file(ifstream amp;in_stream);
int main()
{
ifstream in_stream;
cout << "Welcome to the Test Grader." << endl;
get_input_file(in_stream);
}
void get_input_file(ifstream amp;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;
}
Комментарии:
1. Проверьте, не произошел ли
in_stream.open()
сбой внутри бесконечного цикла, и используйтеbreak;
, если нет.
Ответ №1:
возможно, это:
using namespace std;
void get_input_file(ifstream amp;in_stream);
int main()
{
ifstream in_stream;
cout << "Welcome to the Test Grader." << endl;
get_input_file(in_stream);
}
void get_input_file(ifstream amp;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. Это цикл с разрывом в середине. Обычно я использую: for(;;) { … если (!in_stream.fail()) прерывается; cout << «Ошибка»; }
2. Я просто хотел сделать это с минимально возможными изменениями
Ответ №2:
Я не думаю, что ваш цикл do 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());