Redirect both cout and stdout to a string in C++ for Unit Testing

前端 未结 4 1289
一个人的身影
一个人的身影 2020-12-03 02:49

I\'m working on getting some legacy code under unit tests and sometimes the only way to sense an existing program behavior is from the console output.

I see lots of

相关标签:
4条回答
  • 2020-12-03 03:12

    You can use freopen(..., stdout) and then dump the file into memory or a std::string.

    0 讨论(0)
  • 2020-12-03 03:22

    This may be an alternative:

    char bigOutBuf[8192];
    char savBuf[8192];
    
    fflush(stdout);
    setvbuf(stdout,bigOutBuf,IOFBF,8192);//stdout uses your buffer
    
    //after each operation
    strncpy(savBuf,bigOutBuf,8192);//won't flush until full or fflush called
    
    //...
    
    //at long last finished
    setbuf(stdout,NULL);//reset to unnamed buffer
    

    This just intercepts the buffered output, so still goes to console or wherever.

    Hope this helps.

    0 讨论(0)
  • 2020-12-03 03:25

    std::stringstream may be what you're looking for.

    UPDATE
    Alright, this is a bit of hack, but maybe you could do this to grab the printf output:

    char huge_string_buf[MASSIVE_SIZE];
    freopen("NUL", "a", stdout);
    setbuf(stdout, huge_string_buffer);
    

    Note you should use "/dev/null" for linux instead of "NUL". That will rapidly start to fill up huge_string_buffer. If you want to be able to continue redirecting output after the buffer is full you'll have to call fflush(), otherwise it will throw an error. See std::setbuf for more info.

    0 讨论(0)
  • 2020-12-03 03:29

    Try sprintf, that's more efficient.

    int i;
    char str[] = "asdf";
    char output[256];
    sprintf(output, "asdfasdf %s %d\n", str, i);
    
    0 讨论(0)
提交回复
热议问题