gpt4 book ai didi

c++ - 在交互式程序中使用带有 cout 和 stringstream 的预处理器指令 - C++

转载 作者:行者123 更新时间:2023-11-28 02:10:48 25 4
gpt4 key购买 nike

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

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

关于c++ - 在交互式程序中使用带有 cout 和 stringstream 的预处理器指令 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35802909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com