我需要这样做:打开一个用户指定的文件进行输入。提示输入文件名,将其读入字符串变量,回显打印到终端,然后打开它。如果文件没有成功打开,进入一个打印出错误信息的循环,重置输入文件流变量(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()
返回
只是不要那样做。
关于c++ - 为什么这个循环不循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26417592/