【问题标题】:How to make sure cin opened the file properly?如何确保 cin 正确打开文件?
【发布时间】:2012-12-17 08:32:41
【问题描述】:

我有这个代码:

static std :: ifstream s_inF(argv[j]);
std :: cin.rdbuf(s_inF.rdbuf());

我怎样才能确保它正确打开文件并且没有问题?

我的意思是我想写这样的东西:

static std :: ifstream s_inF(argv[j]);
std :: cin.rdbuf(s_inF.rdbuf());
if(.....)
{
  cout << "can not open the file" << endl;
  return 0;
}
...
.....
....
cin.close();

有什么建议吗?

【问题讨论】:

    标签: c++ cout cin istream


    【解决方案1】:

    作为std::basic_ios 子类的所有对象(如您的情况下的s_inFstd::cin)都有一个operator bool,如果流已准备好进行I/O 操作,则返回true。

    这意味着您可以简单地直接测试它们,例如:

    static std::ifstream s_inF(argv[j]);
    std::cin.rdbuf(s_inF.rdbuf());
    if (!s_inF)
    {
      cout << "can not open the file" << endl;
      return 0;
    }
    // ...
    cin.close();
    

    【讨论】:

      【解决方案2】:

      您可以为此使用is_open。见这里:

      http://www.cplusplus.com/reference/fstream/ifstream/is_open/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-15
        • 1970-01-01
        相关资源
        最近更新 更多