Home > Software engineering >  Perform a call to a function that will print character
Perform a call to a function that will print character

Time:02-11

The vga_puts function should print out characters one by one. To do so, it should perform calls to the vga_putc() function that will actually print each character.

void vga_putc(char c) {

  switch (c) {
  case VGA_TAB:

    vga_set_c(0x20);
    vga_incrementpos();
    vga_set_c(0x20);
    vga_incrementpos();
    vga_set_c(0x20);
    vga_incrementpos();
    vga_set_c(0x20);
    vga_incrementpos();

    break;

  case VGA_RETURN:

    pos_x = 0;

    break;

  case VGA_NEWLINE:

    pos_x = 0;
    pos_y  ;

    break;

  case VGA_BACKSPACE:

    if (pos_x == 0) {
      vga_set_xy(79, pos_y--);
    }
    else if (pos_x != 0 && pos_y != 0) {
      pos_x--;
    }
    else if (pos_y == 0) {
      vga_set_xy(pos_x, pos_y);
      break;
    }
  }


  void vga_puts(char* s) {

  }
    

I understand that vga_puts(char *s) has a pointer to character s however I dont understand how to call vga_putc(char c) in order to print it to the screen. I tend to overthink things and I feel like its fairly simple.

CodePudding user response:

It is fairly simple.

You probably just want this:

void vga_puts(char* s) {
  char c;
  while (c = *s  )  // repeat until c is 0
    vga_putc(c);
}
...
int main(void)
{
  vga_puts("Hello\r\nWorld!");
}

This should print this:

Hello
World!

But there are also a problems in vga_putc: you don't handle the case where c is just a normal character that should be printed, and the final } is missing.

The end of vga_putc should look like this:

    ...
    case VGA_BACKSPACE:

      if (pos_x == 0) {
        vga_set_xy(79, pos_y--);
      }
      else if (pos_x != 0 && pos_y != 0) {
        pos_x--;
      }
      else if (pos_y == 0) {
        vga_set_xy(pos_x, pos_y);
        break;
     }

    default:   // handle all other cases, IOW prints the characters

      vga_set_c(c);
      vga_incrementpos();
    }
  }
}   // this '}' was missing

CodePudding user response:

This is quite simple just write a while loop to do so.

Example:

void vga_putc(char c); // fix prototype warning
unsigned long long int vga_puts(const char *s); // if `s` is not going to change inside a function mark it as `const`

void vga_putc(char c)
{
   /// your code
}

unsigned long long int vga_puts(const char *s)
{
  if (!s)
    return 0;
  unsigned long long int len_stdout = 0;
  while (*s)
  {
     vga_putc(*s  );
     len_stdout  ;
  }
  return len_stdout;
}

int main(void)
{
  vga_puts("Hello\nWorld\n");
  return 0;
}
  •  Tags:  
  • c
  • Related