用户输入文件名打开文件



(已解决)(我不知道如何关闭它)我正在尝试接受用户输入以打开源文件中的.dat文件,但我不知道为什么该文件一直无法打开。我已经检查了语法和其他内容,但就是找不到解决方案。

#include <iostream>
#include <string>
#include <fstream>
#include "arrayFunctions.h"
using namespace std;
int main()
{
   string fileName;
   int size = 0;
   ifstream inputFile;
   do
   {
      cout << "Please enter file name: ";
      getline(cin,fileName);
      inputFile.open(fileName.c_str());
      if (!inputFile)
      {
         cout << "The file "" << fileName << "" failed to open.n"
              << "Check to see if the file exists and please try again" 
              << endl << endl;
      }
      while (inputFile.good())
      {
          string stop = " ";
          string num;
          getline(inputFile, stop);
          size++;
      }
    } while (!inputFile);
    cout << size << endl << endl;
    inputFile.close();
    system("pause");
}

问题似乎在于实际打开文件,因为这会使失败

do
{
    ifstream inputFile("num.txt");
    opened = true;
    if (!inputFile.is_open())
    {
        cout << "The file "" << fileName << "" failed to open.n"
             << "Check to see if the file exists and please try again" 
             << endl << endl;
        opened = false;
    }
    inputFile.close();
} while (!opened);

我认为您的问题是inputFile是在堆栈上定义的对象,因此将其直接放入if语句可能并不是在做您认为它在做的事情——它总是对对象的引用,永远不会为null。

我不太确定如果将ifstream隐式转换为布尔值会发生什么。

尝试更改此

if (!inputFile)

if (!inputFile.is_open())

我已经复习了流的引用,特别是good()方法的作用。实际上,它太宽泛了,你无法推断出哪里出了问题——可能是硬盘错误、权限错误、文件名错误等。

如果你使用这样的东西(改编自C++参考)显示错误消息,你会更清楚地了解发生了什么:

if (!inputFile.good()) {
  cout << "The file "" << fileName << "" failed to open.n"
  cout << "good()=" << inputFile.good();
  cout << " eof()=" << inputFile.eof();
  cout << " fail()=" << inputFile.fail();
  cout << " bad()=" << inputFile.bad();
}

最新更新