Search code examples
c++arraysdosborland-c++

string manipulating in C?


I want to print an array of characters, these characters are underscores first. Then the user can write characters on these underscores.I used gotoxy() but it doesn't work properly. That is what i wrote:

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

Solution

  • The first thing is this: You probably don't want to have all those calls to gotoxy, textattr and cprintf in your main function, since that is not what the main function is supposed to do.

    It is much more likely that the main function's purpose is "to read some text from the user, presented nicely in an input field". So you should make this a function:

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