c++ - 用户输入文件名打开文件

标签 c++ file filenames

(已解决)(我不知道如何关闭它)我正在尝试接受用户输入以打开源文件中的 .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 隐式转换为 bool 值会发生什么情况。

尝试改变这个

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();
}

关于c++ - 用户输入文件名打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37018468/

相关文章:

c++ - OpenCV 和 Xcode

c++ - C++11 中一个好的 std::string 跨平台 UTF8 替代品?

jquery - 我可以使用 jquery 从具有 multiple 属性的输入 type=file 读取文件名数组吗?

c++ - std::getline 从 istream 到 string[] 多次空白

python - 字符串到 unix 文件名的可逆编码

php - 是否有任何理由使用 jpg 文件扩展名?

macos - sem_open 在 Mac OS X 10.6.6 HFS+ 上为少于 64 个字符的名称设置 ENAMETOOLONG

c++ - DLL包装器和DLL之间的区别

C++ 将不同的数据类型打包到一个 long 变量中

C简单文件整数计数程序实现问题