Easy to print verbose debug output?

I am mainly looking for a way to automate text input as follows:

cout << "a[" << x << "][" << y << "] =\t" << a[x][y] << endl;

Sort of:

PRINTDBG(a[x][y]);

Ideally, this will also work for

PRINTDBG(func(arg1, arg2));

and even

PRINTDBG(if(condition) func(foo););

(which will print, for example, "if (false) func (5)").

Intolerable hacks are also welcome :)

(no, using a debugger is not the same, it is much less flexible, and I find it confusing)

+3
source share
5 answers

This is the way you want it, impossible. If you have (condition) func (foo); given to the macro, it can align this stuff and it will print if (condition) func (foo); but not with the actual values ​​of the replaced variables. Remember that the preprocessor is not aware of the structure of this code.

, printf, boost.format - brew printf boost.fusion, , :

dprintf("a[%][%] = %", (x, y, a[x][y]));
+2

, printf :

cout << "a[" << x << "][" << y << "] =\t" << a[x][y] << endl;
printf("a[%d][%d] =\t%d\n", x, y, a[x][y]);

, , printf, - .

, Boost - , , .

. :

#define PRINTDBG(x) cout << #x << " =\t" << x << endl;

, PRINTDBG(a[x][y]), :

a[x][y] = 5

x y.

+2

,


Log(const char *format, ...)
{
    char buffer[MAX_BUFFER_SIZE];
    va_list args;

    //get arguements into a list
    va_start(args, format);

    //printf formated arguement into a string
    vsnprintf(buffer, sizeof(buffer), format, args);

    va_end(args);

    printf("%s", buffer);
  }

Log("a[%d][%d] =\t%d\n", x, y, a[x][y])
Log("if(%s) func(%d) ;", (condition) ? "true" : "False", func(foo))

add in some loggingtype (i.e. LOG_SCREEN, LOG_FILE) to the function Log() and now you can control where is gets logged to

add in some logginglevel (i.e. WARN, CRIT) to control how it gets displayed, color etc.

Of course there are many, many library out there that do all this type of stuff already

hope this helps

0

Greg C, .

#DEFINE DEBUG_MODE 1
//...
if( DEBUG_MODE)
  printf("methodX() says: y=%i, var1=%i", y, var1);

printf , , .

0

you can define the operator for custom classes, so you only need to define the formatting once:

struct point3 {
      int x,y,z;
      point3(int a, int b, int c){x=a;y=b;z=c;}
};

std::ostream& operator << (std::ostream& os, const point3& f) {
      return os << "(" << f.x << "," << f.y << "," << f.z << ")";
}

point3 p(1,2,3);
std::cout << p; // prints "(1,2,3)"

these pairs are good with redirecting cout or clog to a file (don't remember how std :: clog works)

#include <iostream>
#include <fstream>

int main() {
      std::ofstream file("log.txt");
      std::streambuf *filebuf = file.rdbuf();
      std::cout.rdbuf(filebuf);

      std::cout << "This is written to the file";

      filestr.close();
      return 0;
}
0
source

All Articles