2013-02-17 124 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