Mit Glibc stdio Swapping, kann ich eine memstream für stdout tauschen, wodurch die Ausgabe eines Stück Code zur Ausgabe an stdout zusammengestellt Erfassung:eine string für cout
#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);
}
Ich bin gespannt, ob die gleiche möglich für iostreams
. Mein naiver Versuch wird nicht kompiliert:
#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;
}
Keine Spam-Tags! C ist eine andere Sprache! – Olaf
'std :: cout.rdbuf (ss.rdbuf())', aber realistischerweise würden Sie 'int cc_capt (std :: ostream &)' definieren und den Stream übergeben. – user657267