使用 glibc 的 stdio,我可以将 memstream 换成 stdout,从而捕获一段编译后的代码输出到 stdout:
#include <stdio.h>
void swapfiles(FILE* f0, FILE* f1){ FILE tmp; tmp = *f0; *f0 = *f1; *f1 = tmp; }
void hw_c(){ puts("hello c world"); }
int c_capt(){
FILE* my_memstream;
char* buf = NULL;
size_t bufsiz = 0;
if( (my_memstream = open_memstream(&buf, &bufsiz)) == NULL) return 1;
FILE * oldstdout = stdout;
swapfiles(stdout, my_memstream);
hw_c();
swapfiles(stdout, my_memstream);
fclose(my_memstream);
printf("Captured: %s\n", buf);
}
我很好奇 iostreams
是否也可以这样做。
我天真的尝试不会编译:
#include <iostream>
#include <string>
#include <sstream>
void hw_cc(){ std::cout<<"hello c++ world\n"; }
int cc_capt(){
using namespace std;
stringstream ss;
string capt;
//std::swap(ss,cout); //<- the compiler doesn't like this
hw_cc();
//std::swap(ss,cout);
cout<<"Captured: "<<capt<<'\n';
}
int main(int argc, char** argv){
c_capt();
puts("---------------------------------");
cc_capt();
return 0;
}
最佳答案
你可以,但你不会交换整个流——只是流缓冲区。
void cc_capt() {
using namespace std;
stringstream ss;
auto orig = std::cout.rdbuf(ss.rdbuf());
hw_cc();
std::cout.rdbuf(orig);
std::cout << "captured: " << ss.str() << "\n";
}
请注意,在这种情况下,我们并没有真正使用 stringstream
本身,只是stringbuf
它包含。如果我们愿意,我们可以定义一个 basic_stringbuf<char>
并直接使用它而不是定义 stringstream
然后只使用 stringbuf
它包含。
关于c++ - 将 stringstream 换成 cout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37758378/