0

所以如果我有一个像这样的简单交互式程序:

#include <iostream>
#include <sstream>
#include <string>
#include <cstring>
#define cout os

int main() {

    stringstream os;

    cout << "If you would like to continue, type 'Continue'" << '\n';

    string line;
    while (cin >> line) {

        if (line == "Continue") {
            cout << "If you would like to continue, type 'Continue'" << '\n';
        }

        else { break; }
    }

    cout << "Program ended." << '\n';

    cout << os.str();
    return 0;
}

我如何使它能够包含我的指令“#define”,以便打印到标准输出的所有行都将在程序末尾由 cout << os.str() 打印,当这样做时它还会将最终的“cout”变成“os”吗?我已经尝试在最后使用 printf 而不是 os,并且遇到了麻烦/编译器错误,说“没有对 printf 的匹配函数调用”。

我希望我的问题是有道理的,如果这个问题已经被问过,但我在这里找不到它,我深表歉意。

4

2 回答 2

2

您不需要(分别想要)预处理器宏来实现这一点。只需将要打印的代码放入函数中:

void writeToStream(std::ostream& os) {
    os << "If you would like to continue, type 'Continue'" << '\n';

    string line;
    while (cin >> line) {

        if (line == "Continue") {
             os << "If you would like to continue, type 'Continue'" << '\n';
        }

        else { break; }
    }

    os << "Program ended." << '\n';
}

并根据需要调用它main()

int main() {
#ifdef TOSCREEN
    writeToStream(cout);
#else
    std::stringstream os;
    writeToStream(os);
#endif
    cout << os.str();
    return 0;        
}
于 2016-03-04T18:18:19.537 回答
0

将 STL 中的名称用作预编译器定义是一种不好的做法。如果您想要将其重定向std::cout到您的,std::stringstream那么您可以通过std::cout::rdbuf以下方式使用:

#include <iostream>
#include <sstream>
#include <string>
#include <cstring>

using namespace std;

int main() {
    stringstream os;

    // redirect cout to os
    auto prv = cout.rdbuf(os.rdbuf());

    cout << "If you would like to continue, type 'Continue'" << '\n';

    string line;
    while (cin >> line) {

        if (line == "Continue") {
            cout << "If you would like to continue, type 'Continue'" << '\n';
        }

        else { break; }
    }

    cout << "Program ended." << '\n';

    // restore cout to its original buffer
    cout.rdbuf(prv);

    cout << os.str();

    return 0;
}
于 2016-03-04T18:00:47.970 回答