[英]Using preprocessor directives with cout and stringstream in interactive program - C++
因此,如果我有一个简单的交互式程序,例如:
#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。”
我希望我的问题有道理,如果已经提出这个问题,我深表歉意,但我在这里找不到。
您不需要(分别想要)预处理器宏来实现此目的。 只需将要打印的代码放入函数中:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.