c++ - 为什么这个循环不循环?

标签 c++

我需要这样做:打开一个用户指定的文件进行输入。提示输入文件名,将其读入字符串变量,回显打印到终端,然后打开它。如果文件没有成功打开,进入一个打印出错误信息的循环,重置输入文件流变量(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/

相关文章:

c++ - c++中以下类似的语句有区别吗?

c++ - 从 Swift 中的泛型参数继承的替代方法

c++ - Sieve of Eratosthenes 算法的效率

android - 将 vector<string> 从 C++ 返回到 Java

类中类的 C++ 对象未授予公共(public)访问权限

c++ - x86-64 长 double

c++ - 使用来自控制台的输入来分割列表的故障初始化 vector

c++ - 如何返回指向链表中最大值的指针?

c++ - 如何定时同步线程?

c++ - 制作结构数组?