在交互式程序中将预处理器指令与 cout 和字符串流一起使用 - C++

Using preprocessor directives with cout and stringstream in interactive program - C++

本文关键字:字符串 一起 C++ cout 程序 交互式 预处理 指令 处理器      更新时间:2023-10-16

所以如果我有一个简单的交互式程序,比如:

#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 代替操作系统,并且遇到了问题/编译器错误,说"没有匹配的函数调用 printf"。

我希望我的问题有意义,如果已经问过这个问题,我深表歉意,但我无法在这里找到它。

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

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;        
}

使用 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;
}