【问题标题】:User Input filename open file用户输入文件名打开文件
【发布时间】:2016-08-29 08:16:35
【问题描述】:

(已解决)(我不知道如何关闭它)我正在尝试接受用户输入以打开源文件中的 .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);

【问题讨论】:

  • 你确定文件在它应该在的地方吗?例如,如果用户输入 foo.txt,则 foo.txt 文件必须位于进程的工作目录所在的任何位置
  • @Jerry Jerehmiah 显然我需要将文件移动到实际的源代码文件夹,而不是将其拖到 Microsoft Visual Studio 上的源代码文件夹。我选择你的作为答案,但它是一个评论
  • 只需接受一个答案(如果正确)或写下您自己的答案并接受它

标签: c++ file filenames


【解决方案1】:

我认为您的问题是 inputFile 是在堆栈上定义的对象,因此将其直接放入 if 语句可能不会像您认为的那样做 - 它始终是对对象的引用,并且永远不会为空。

我不太确定如果将 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();
}

【讨论】:

  • 那行不通。但是 ifstream 提供了诸如 good 和 fail 之类的功能,我尝试了相同的结果。文件好像打不开
  • @Darr Brett 我意识到我的错误是由于当我将文件拖到解决方案资源管理器中的源代码文件夹时,Visual Studio 没有将文件移动到其目录。我不得不在文件资源管理器本身中移动文件。不管它有用的是知道 /i 可以用错误做到这一点
猜你喜欢
  • 2014-04-11
  • 2019-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-25
  • 1970-01-01
  • 2016-04-02
  • 2022-01-05
相关资源
最近更新 更多