cerr未定义

时间:2010-11-01 12:53:53

标签: c++

我遇到了一些问题,我收到了这些错误(在代码中标明):

  • 标识符“cerr”未定义
  • 无操作员“<<”匹配这些操作数

为什么?

#include "basic.h"
#include <fstream>

using namespace std;

int main()
{

    ofstream output("output.txt",ios::out);
    if (output == NULL)
    {
        cerr << "File cannot be opened" << endl;   // first error here
        return 1;
    }

    output << "Opening of basic account with a 100 Pound deposit: "
        << endl;
    Basic myBasic (100);
    output << myBasic << endl;   // second error here
}

4 个答案:

答案 0 :(得分:17)

您必须包含iostream才能使用cerrhttp://en.cppreference.com/w/cpp/io/basic_ostream

答案 1 :(得分:9)

您需要在顶部添加:

#include <iostream>

用于cerr和endl

答案 2 :(得分:9)

包括用于cerr支持的iostream。

并没有运营商&lt;&lt;的实现对于Basic类。你必须自己做这个实现。见here.

答案 3 :(得分:2)

#include <fstream>
#include <iostream>

#include "basic.h"


std::ostream& operator<<(std::ostream &out, Basic const &x) {
  // output stuff: out << x.whatever;
  return out;
}

int main() {
  using namespace std;

  ofstream output ("output.txt", ios::out);
  if (!output) {  // NOT comparing against NULL
    cerr << "File cannot be opened.\n";
    return 1;
  }

  output << "Opening of basic account with a 100 Pound deposit:\n";
  Basic myBasic (100);
  output << myBasic << endl;

  return 0;
}