c++ - 使用和 if/else 语句输出到屏幕或文件

标签 c++ if-statement

我正在为一个类编写一个程序,它有一个虚拟输出函数和一个迭代器,它可以输出到具有特定逻辑的屏幕或输出到具有特定逻辑的文件。我遇到的问题是它在应该调用 else 的情况下调用了 IF 部分。想知道是否有人可以阐明这一点。

调用输出函数:

    ofstream fout;
    fout.open("save.txt");
    if (!fout.fail()){
        for (list<pethousedotcom*>::iterator it = homelist.begin(); it != homelist.end(); it++)
            (*it)->output(fout);     //<-- calling function below still calling the one that is only supposed to be for cout

输出函数:

void bird::output(ostream& os) const {
    if (os == cout) {
            //still being executed
    }    
    else {
            // being skipped
    }
}

这里有什么明显的错误吗?或任何建议?

最佳答案

"Anything obvious wrong here?"

假设你的文件打开成功,语句

if (os == cout) {
        //still being executed
}    

只是比较the state (results of the std::basic_ios::operator void*())这两个 std::ostream 实例的计算结果很可能对它们都为 true

"any advice?"

如果你想区分os实际上等于cout你可以比较他们的地址:

if (&os == &cout) {
    // not being being executed when writing to std::cout
}    

关于c++ - 使用和 if/else 语句输出到屏幕或文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29333367/

相关文章:

c++ - 如何替换数值对应的二维 vector ?

c++ - Borland 中的 bcc32 和 bcc32ide 有什么区别?

MySQL 查询 - IF 或 CASE 以及 AND 和异常(exception)(用于计算)

javascript - Drop down 中的数据绑定(bind)

php - 检查变量是否为空

c - 获取错误 : "variable cannot appear in a constant-expression"

c++ - 类似 C 的回调处理 : which algorithm preforms faster?

c++ - boost 是否提供 make_zip_range?

c++ - 如何将 Perl 嵌入到 C++ 应用程序中?

if-statement - 一般编程 - else 或 else if 为清楚起见