“阻止”下一个cout

时间:2018-03-27 21:44:10

标签: c++ std stdout cout

我想知道是否有办法为少数下一个字符或下一个命令“阻止”cout输出。 我有一个功能,我不能在开头用打印更改,并希望覆盖下一个打印。

workon

我知道有一种方法可以暂时禁用输出,但由于我无法修改打印功能以在第一次打印后启用它,所以我真的不知道该怎么做。可以只复制整个函数,但那不太好。

1 个答案:

答案 0 :(得分:2)

我很好奇,并在此代码审核https://codereview.stackexchange.com/q/104428/38143帖子的启发下撰写了这个概念验证。使用std::codecvt进行此操作可能是愚蠢的,并且代码可能包含错误,因此使用风险自负:

#include <locale>
#include <algorithm>
#include <iostream>
#include <iomanip>

class swallow_line_facet : public std::codecvt<char, char, std::mbstate_t> {
public:
    swallow_line_facet(std::size_t ref = 0)
        : std::codecvt<char, char, std::mbstate_t>(ref) {}

protected:
    result do_out(
        state_type &,
        const intern_type* from,
        const intern_type* from_end,
        const intern_type*& from_next,
        extern_type* to,
        extern_type* to_end,
        extern_type*& to_next) const override
    {
        if (is_done)
            return std::codecvt_base::noconv;

        for (; (from < from_end) && (to < to_end); from++) {
            char c = *from;

            if (is_done)
                *to++ = c;

            if (c == '\n')
                is_done = true;
        }

        from_next = from;
        to_next = to;

        return from == from_end
            ? std::codecvt_base::ok
            : std::codecvt_base::partial;
    }

    virtual bool do_always_noconv() const noexcept override {
        return is_done;
    }

private:
    mutable bool is_done = false;
};

std::ostream& swallow_line(std::ostream& out)
{
    out.imbue(std::locale(out.getloc(), new swallow_line_facet));
    return out;
}

演示

int main() {
    /// This probably has to be called once for every program:
    // http://stackoverflow.com/questions/26387054/how-can-i-use-stdimbue-to-set-the-locale-for-stdwcout
    std::ios_base::sync_with_stdio(false);

    std::cout << "first line" << '\n' << swallow_line;
    std::cout << "second line" << '\n';
    std::cout << "third line" << '\n' << swallow_line;
    std::cout << "fourth line" << '\n';
    std::cout << "fifth line" << '\n';
}

输出:

first line
third line
fifth line

在您的情况下使用:

void overridePrint(){
    std::cout << "Replaced header" << std::endl;
    std::cout << swallow_line;
    print();
}

int main() {
    /// don't forget this
    std::ios_base::sync_with_stdio(false);
    // ...
}