views:

125

answers:

3

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

Printing an array of characters is fairly easy:

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

From memory that should print a string out to the screen.

Robert Massaioli
Though looking at your code I am not sure that I understand your question properly.
Robert Massaioli
when i run there must be underscores already printed, number of underscores is the no. of elements in the array.Then the pointer of writing must be at the first underscore and when i write any character, it will be written in that exact position and stored in the array.
noor
Oh, I see what you want. And you are doing it the wrong way. Curses or Ncurses, as suggested above, would make your life that much easier.
Robert Massaioli
A: 

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;
}
Roland Illig
A: 

Your code is very DOS-specific. There is not a good general solution to the problem of reading immediate input in a portable way. It does get asked quite often, so I think the C FAQ broke down and included an answer which you might want to seek out.

That said, I think your bug is that gotoxy(1, 1) is the upper corner of the screen, not 0,0. So you want gotoxy(i, 1)

Ben Jackson