在交互式程序中将预处理器指令与 cout 和字符串流一起使用 - C++
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 代替操作系统,并且遇到了问题/编译器错误,说"没有匹配的函数调用 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;
}
相关文章:
- 有没有办法在C++将字符串与开关语句一起使用?
- 我如何将 OR 与 if 语句一起使用字符串
- 如何将两个字符串加在一起,就好像它们是变量一样?
- 将 NULL 与 C 的字符* 字符串一起使用
- C++程序在将 int 与 cin 一起使用时有效,但不能使用字符串
- 编译器如何将链表中的地址字符串在一起?
- 将find_last_of与字符串C++一起使用
- 在 c++ 中将 find_first_of 与字符串一起使用,而不是一组预定义字符
- 如何将adjacent_find与字符串C++一起使用
- 可以将std::getline()与从std::string中移出的字符串一起使用吗
- 如何在不使用模板的情况下将variadic函数与字符串一起使用
- 将 dirent->d_name 与字符串一起使用失败
- 如何将开关与字符串一起使用
- 将两个字符串一起分配,获取访问读取冲突
- C++ - 将 sendto() 与基本字符串一起使用
- 如何在C++中将 atoi 函数与字符串一起使用
- 将 <null> printf 与字符串一起使用
- 除非我通过data()或C_str()运行cout,否则无法将它与C++字符串一起使用
- C++-将.at()方法与字符串一起使用时出现问题
- 如何将replace_if与字符串一起使用