Frage

I currently have this function to print out every rows of my tables

static int callback(void *NotUsed, int argc, char **argv, char **szColName)
{
    for(int i = 0; i < argc; i++)
    {
        cout.width(17); cout << left << argv[i];
    }

    std::cout << "\n";

    return 0;
}

How do I print out szColName, such that it only appear once on top, and not multiple occurences of it? Tried this:

static int callback(void *NotUsed, int argc, char **argv, char **szColName)
{
    int n = sizeof(szColName) / sizeof(szColName[0]);
    for (int i = 0; i < n; i++)
    {
        cout.width(17); cout << left << szColName[i];
    }
    printf("\n");
    for(int i = 0; i < argc; i++)
    {
        cout.width(17); cout << left << argv[i];
    }

    std::cout << "\n";

    return 0;
}

But it outputs everytime after a outputting the row values

War es hilfreich?

Lösung

You might want to declare a static bool inside callback to record whether it has already printed out the column names. Or, if you want to be able to reset it...

such as:

static bool firstline = true;

static int callback(void *NotUsed, int argc, char **argv, char **szColName)
{
if (firstline){
    int n = sizeof(szColName) / sizeof(szColName[0]);//this is incorrect but fixing
                                                 // it requires changing the prototype. 
                                                  //See the comments below
    for (int i = 0; i < n; i++)
    {
        cout.width(17); cout << szColName[i] << left;
    }
    printf("\n");
    firstline=false;
}
for(int i = 0; i < argc; i++)
{
    cout.width(17); cout << argv[i] << left;
}

std::cout << "\n";

return 0;
}
int main(){
    for(int x=0;x<10;++x)callback( ... , ... , ... ); // give whatever argument you need to give

    firstline = true;  //reset the variable so that next time you call it, the col names will appear
    for(int x=0;x<10;++x)callback(...,...,...);// now the col names will appear again.
}

I assume that what you provide would print out the rows and the column names correctly. I only added a variable to check if printing column names are needed.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top