【问题标题】:File stream with repeating input具有重复输入的文件流
【发布时间】:2018-04-09 05:51:42
【问题描述】:

我正在尝试创建一个重复菜单,如果程序无法打开文件,该菜单将允许用户重新输入文件名。

现在,如果我输入现有文件的名称,它可以正常工作,但如果文件不存在,它会打印“找不到文件”,然后执行程序的其余部分。我是文件流的新手,这里的大部分代码都是通过引用找到的。我对到底发生了什么以及处理这种情况的最佳方法有点迷茫。任何指导将不胜感激。

typedef istream_iterator<char> istream_iterator;    

string fileName;

ifstream file;

do {        
    cout << "Please enter the name of the input file:" << endl;
    cin >> fileName;

    ifstream file(fileName.c_str());

    if (!file) {
        cout << "File not found" << endl;
    }

} while (!file);

std::copy(istream_iterator(file), istream_iterator(), back_inserter(codeInput));

【问题讨论】:

  • 您在循环中声明了一个与外部文件同名的变量。将ifstream file (fileName.c_str()); 更改为file = std::ifstream(fileName); 应该没问题。

标签: c++ do-while ifstream


【解决方案1】:

在构造对象file 之后会一直存在,所以你的循环条件总是会失败。将条件改为文件是否没有正常打开。

do {
...
}
while (!file.is_open())

【讨论】:

  • 请不要接受我的回答,错误多于正确,Arkady Godlin 下面的回答更值得被接受。
【解决方案2】:

此代码将起作用。

do {
    std::cout << "Please enter the name of the input file:" << std::endl;
    std::cin >> fileName;

    file = std::ifstream(fileName.c_str());

    if (!file) {
        std::cout << "File not found" << std::endl;
    }

} while (!file);

你的错误是你有两个文件变量的定义。 while (!file) 中使用的变量是在 do-while 循环之外定义的变量,并且它的有效状态默认设置为 true。

【讨论】:

    【解决方案3】:

    除了@acraig5075 回答:

    写一个类型然后一个变量名(ifstream file)就是创建一个新变量。显然你知道这一点,但如果你在例如循环中再次使用相同的名称,它会生成一个新的不同变量。

    ifstream file; // a unique variable
    ...
    do {
        ...
        ifstream file(fileName.c_str()); // another unique variable
    

    ...所以将循环内的用法更改为:

        file.open(fileName.c_str());
    

    【讨论】:

      猜你喜欢
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 2020-11-17
      相关资源
      最近更新 更多