-3

I'm pretty bad at using char*'s in C/C++ and am asking for such an effect:

Say I have a text editor or viewer and I want to show line numbers on the side. My implementation would be the following (please point out any faults in this if possible):

unsigned int line_number_width = 5;
char* lines = strdup(buffer->text);
char* line = strtok(lines, "\n");
unsigned line_number = 1;
while (line != NULL && line_number<= buffer->height) {
    printf("???:%.*s\n", !!line_number, line_number_width!!, buffer->width - line_number_width - 1, line);
    line = strtok(NULL, "\n");
    line_number++;
}
free(lines);

I want the following to print out:

  1:line1
  2:line2
  3:line3
  4:line4
  5:line5
  6:line6
  7:line7
  8:line8
  9:line9
 10:line10
..........
..........
..........
..........
..........
..........
..........
..........
100:line100

Notice how the :'s are all aligned in the same column.

What should I replace ??? with so that I get the following effect where the number passed is enclosed in a rectangle of length line_number_width, which are the arguments between !!..!!, such that the passed number is justified right in that imaginary rectangle?

A M
  • 14,694
  • 5
  • 19
  • 44
Apoqlite
  • 239
  • 2
  • 21
  • 2
    No such language as C/C++, it's clear that you are really programming in C. – john May 19 '20 at 05:27
  • 2
    Doesn't `%*d` work for you? – john May 19 '20 at 05:29
  • Read [*how to debug small programs*](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and [more](https://en.cppreference.com/w/c) about [C11](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) – Basile Starynkevitch May 19 '20 at 05:39

1 Answers1

-1

OK, I think I got an answer:

unsigned int line_number_width = 5;
char* lines = strdup(buffer->text);
char* line = strtok(lines, "\n");
unsigned line_number = 1;
while (line != NULL && line_number<= buffer->height) {
    printf("%*d%.*s\n", line_number_width-(unsigned int)(log10(line_number)), line_number, buffer->width - line_number_width, line);

    line = strtok(NULL, "\n");
    line_number++;
}
free(lines);
Apoqlite
  • 239
  • 2
  • 21