2010-10-19 74 views
-1

我想打印一個字符數組,這些字符首先是下劃線。 然後用戶可以在這些下劃線上寫字符。我用gotoxy(),但它不能正常工作。 這是我寫的:在C中操縱字符串?

int main(void) 
{ 
    char arr[20]; 
    int i; 
    char ch; 
    clrscr(); 

    for(i=0;i<=20;i++) 
    { 
     textattr(0x07); 
     cprintf("_"); 
    } 

    do 
    { 
     for(i=0;i<=20;i++) 
     { 
      //gotoxy(i,0); 
      //ch = getche(); 
      if(isprint(ch) == 1) 
      { 
       arr[i] = ch; 
       gotoxy(i,0); 
       //printf("%c",ch); 
      } 
     } 
    } while(i == 20); 

    getch(); 
    return 0; 
} 
+2

我很樂意回答,但請清理你的問題降價。每行代碼前四個空格縮進。 – 2010-10-19 22:06:24

+0

你使用什麼編譯器? conio.h沒有得到很好的支持(如果有的話),如果你不使用Borland,也許這就是爲什麼你不能正確工作?你有沒有試過詛咒? – mingos 2010-10-19 22:07:33

+0

我使用的是Borland C++ – noor 2010-10-19 22:10:13

回答

0

首先是這樣的:你可能不希望在主函數中有所有這些調用gotoxy,textattrcprintf,因爲這不是主要功能應該做的。

主要功能的目的很可能是「從用戶讀取一些文本,在輸入字段中很好地呈現」。所以你應該使這個功能:

static int 
nice_input_field(char *buf, size_t bufsize, int x, int y) { 
    int i, ch; 

    gotoxy(x, y); 
    for (i = 0; i < bufsize - 1; i++) { 
    cprintf("_"); 
    } 

    i = 0; 
    gotoxy(x, y); 
    while ((ch = readkey()) != EOF) { 
    switch (ch) { 

    case '...': /* ... */ 
     break; 

    case '\b': /* backspace */ 
     cprintf("_"); 
     i--; 
     gotoxy(x + i, y); 
     break; 

    case '\t': /* tabulator */ 
    case '\n': /* enter, return */ 
     buf[i] = '\0'; 
     return 0; /* ok */ 

    default: /* some hopefully printable character */ 
     if (i == bufsize - 1) { 
     cprintf("\a"); /* beep */ 
     } else { 
     buf[i++] = ch; 
     gotoxy(x + i, y); 
     cprintf("%c", buf[i]); 
     } 
    } 
    } 

    /* TODO: null-terminate the buffer */ 
    return 0; 
} 
0

打印字符數組是相當容易:

char* str = your_array; 
while(*str) { 
    putc(*str++); 
} 

從內存應打印字符串輸出到屏幕。

+0

儘管查看您的代碼,但我不確定是否正確理解了您的問題。 – 2010-10-19 22:09:48

+0

當我在那裏運行時必須有已經打印的下劃線,下劃線的數目是否定的。然後寫入指針必須在第一個下劃線處,當我寫入任何字符時,它將被寫入該確切位置並存儲在數組中。 – noor 2010-10-19 22:15:29

+1

哦,我明白你想要什麼。而你正在做錯誤的方式。如上所述,Curses或者Ncurses會讓你的生活變得更容易。 – 2010-10-19 22:18:12

0

你的代碼是非常特定於DOS的。以便攜方式讀取即時輸入的問題沒有一個好的通用解決方案。它經常被問到,所以我認爲C FAQ已經崩潰了,並且包含了一個你可能想要找到的答案。

這就是說,我認爲你的bug是gotoxy(1, 1)是屏幕的上角,而不是0,0。所以你想gotoxy(i, 1)