2013-02-17 148 views
0

我现在有这个功能,打印出我的表的每一行打印出表的列名

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; 
} 

我如何打印出szColName,使得其仅在顶部出现一次,而不是它多次出现? 尝试这样:

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; 
} 

但后输出行值

+0

但我不认为'sizeof(szColName)/ sizeof(szColName [0])'给出'n'。划分两个指针的大小可能会给你'1'。 – phoeagon 2013-02-17 10:33:57

+0

您可能会在调用函数时第一次打印标题(以及关于何处保留此“第一次”标志,请查看'void * NotUsed')。 – 2013-02-17 10:34:24

回答

0

您可能要声明一个static bool内回调记录是否已经打印出来的列名输出每次。或者,如果您希望能够将其复位......

如:

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. 
} 

我假设你提供将打印出的行和列名正确的。我只添加了一个变量来检查是否需要打印列名。

+0

噢,是的,做了这个工作,但'int n = sizeof(szColName)/ sizeof(szColName [0]);'应该是'int n = sizeof(szColName);'如果我想打印出所有szColName。不过谢谢! – 2013-02-17 10:45:04

+0

哦,等等,我发现了一些东西,当我试图再次执行时,cols消失了。 – 2013-02-17 11:03:51

+0

@WongChunKiat没错。但实际上我不太了解你的规格。如果您需要打印col名称,请将'firstline'更改为全局变量,以便您可以重置它。 – phoeagon 2013-02-17 11:42:03