Следующий код должен получить текстовый файл и прочитать все его строки и напечатать их на консоли, но, хотя он правильно сохраняет fname, после этого он ничего не сделает. Я ценю, если вы можете сообщить мне, в чем проблема.
EDIT: Чтобы быть более точным, я в конечном итоге захочу вызвать несколько функций внутри блока else, но сначала мне нужно выяснить, почему моя программа не доходит до этого.
int main()
{
string fname = "", line, content;
ifstream ifs; // input file stream
string command = "";
int k;
cout << "---- Enter your command and the file name : ";
while (getline(cin, line)){
int i = 0;
for (i = 0; i<line.length(); i++) {
command += line[i];
if (line[i] == ' ')
{
break;
}
}
for (int j = i + 1; j<line.length(); j++)
{
fname += line[j];
}
cout << command;
}
if (command == "exit ")
{
exit(EXIT_SUCCESS);
}
// tries to open the file whose name is in string fname
ifs.open(fname.c_str());
if (ifs.fail()) {
cerr << "ERROR: Failed to open file " << fname << endl;
ifs.clear();
}
else { //do getline here to read content
while (getline(ifs, content))
{
cout << "Content " << k++ << " : " << content << endl;
//Call functions here later
}
}
ifs.close(); // always remember to close it
cout << "---- Enter another file and command name : ";
}
Получил это сам. Я закрыл цикл while слишком рано. Он должен быть закрыт после ifs.close(); вместо.