与互动节目cout和stringstream的使用预处理指令 - C++
问题描述:
,所以如果我有这样一个简单的互动节目:与互动节目cout和stringstream的使用预处理指令 - 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匹配的函数调用”。
我希望我的问题是有道理的,如果已经有人问我这个问题,但我一直无法在这里找到它。
答
使用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;
}
答
你并不需要(分别需要)预处理宏来实现这一目标。只要把你想打印出来成一个函数的代码:
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#define' ++。这是很容易的部分。我不确定你想要做什么。也许你应该展示你的尝试?您可能需要将'os.str()。c_str()'传递给'printf()'。 –
我不明白你想要完成什么。如果要写入标准输出,可以使用'std :: cout',如果要将输出保存为字符串,请使用'std :: ostringstream'。不要使用'#define cout os',因为它是邪恶的。 –
是你的问题“我可以这样做,所有输出到'std :: cout'也被收集在我的'stringstream''”或者你想使用'stringstream'而不是'std :: cout'吗? – molbdnilo