【问题标题】:constructor opens a file with a given filename c++构造函数打开具有给定文件名的文件 c++
【发布时间】:2015-11-15 23:16:33
【问题描述】:

在下面的代码中发生错误并且程序将无法运行,我需要创建一个必须打开具有给定文件名的文件的构造函数。如果文件名不存在,则打印错误消息并终止程序。

以下是我迄今为止在 C++ 中完成的代码:

#include "ReadWords.h"
#include <iostream>
#include <cstdlib>

using namespace std;

ReadWords::ReadWords(const char filename[])
{
    wordfile.open(filename);
    if (!wordfile)
    {
        cout << "cannot make " << filename << endl;
        exit(1);
    }
}

void ReadWords::close()
{
    wordfile.close();
}

【问题讨论】:

  • 当您说“发生错误”时,您能更具体一点吗?什么错误?他们说什么?它们是编译时错误还是运行时错误?
  • 你能把所有的代码贴出来吗?这看起来只是其中的一部分。
  • wordfile的类型是什么?
  • 把自己的includes放在标准includes之后比较正常

标签: c++ file constructor


【解决方案1】:

为什么不尝试将 fstream 包含在文件顶部,看看是否可行

【讨论】:

    【解决方案2】:

    我想wordfile 的类型是std::fstream。如果你的 ReadWords.h #includes &lt;fstream&gt;,它应该可以工作 (compiles and works as expected)。

    顺便说一句,使用using namespace std; 是一种不好的做法。

    另外,由于您使用 C++,请查看std::string。它比使用普通的char*char[] 更安全。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-19
      相关资源
      最近更新 更多