为什么这个循环不循环?

为什么这个循环不循环?

问题描述:

我需要这样做:打开用户指定的文件进行输入。提示文件的名称,将其读入一个字符串变量,echo将其打印到终端,然后打开它。如果文件未成功打开,进入一个打印出错信息的循环,重置输入文件流变量(Input_file_stream_var.clear();其中Input_file_stream_var是输入文件流变量的名称),获取新文件名并尝试打开新文件。循环继续,直到用户成功输入有效的文件名或按ctrl-c退出。为什么这个循环不循环?

这里是我到目前为止的代码,但我不能让它回到过程中,如果文件没有打开。

#include <iostream> 
#include <fstream> 
#include <string> 
#include <sstream> 
#include <iomanip> 
using namespace std; 

int main() 
{ 
    // Variables 
    char test; 
    string infname, outfname; 
    fstream infile, outfile; 
    do 
    { 
     // Propt for and echo print input file 
     cout << endl << "Enter the name of the input file: "; 
     cin >> infname; 
     cout << infname << endl; 

     infile.open(infname.c_str()); 

     // Test if file opened 
     if(!infile) 
     { 
      cout << string(12,'*') << " File Open Error " << string(12,'*') << endl; 
      cout << "==> Input file failed to open properly!!\n"; 
      cout << "==> Attempted to open file: " << infname << endl; 
      cout << "==> Please try again...\n"; 
      cout << string(41,'*') << endl; 
      infile.clear(); 
      return 1; 
     } 
    } while(!infile.is_open());  

    return 0; 
} 

return 1语句导致程序退出:您是从main()

回国只是不这样做。

尝试删除return 1或将其更改为continuereturn 1main返回代码执行,而不是循环。