1

I have a need to print a variable number of a given character in conjunction with my formatted output. I was looking for something similar or equivalent to the VBA function String(num, char), but haven't been able to find any. I've written a function to do the job but if there is something built-in that does it I'd love to know. Here's what I have. For the purpose of testing I'm using a sloppy implementation of argv[].

What I want to is print out something like this;

enter image description here

Here's the rough implementation I've come up with;

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char * make_string(int num,  char character)
{
    char *strchars = malloc(num);
    for (int i = 0; i < num; i++)
        strchars[i] = character;

    return strchars;
}

int main(int argc, char *argv[])
{
    for (int i = 1; i < argc; i++) {
        printf("%s\n", make_string(strlen(argv[i]),'_'));
        printf("%s%c %s\n", make_string(strlen(argv[i]),'_'),'|', argv[i]);
    }
}

Is there a library function for printing strings of repeating characters like this?

Jack Galt
  • 83
  • 8
  • 2
    Your program leaks memory like like a cargo-net roof in a RAM storm. It probably doesn't matter for your demo program, but it would be better to make a habit of ensuring that you free all the memory you allocate. – John Bollinger Feb 29 '16 at 05:32
  • 2
    Also, you must be sure to allow space for a string terminator, and to insert one at the end of each string. – John Bollinger Feb 29 '16 at 05:33
  • 1
    In any case, the C standard library does not contain a function such as you are looking for. – John Bollinger Feb 29 '16 at 05:39
  • 2
    Why go to the trouble/expense of allocating memory and forming a new string? Why not just directly print the character repeatedly in a loop? – kaylum Feb 29 '16 at 05:47
  • 2
    Check this example. I think this will be useful. http://stackoverflow.com/questions/4133318/variable-sized-padding-in-printf – Umamahesh P Feb 29 '16 at 05:49
  • 1
    @John Bollinger ROFL. on the Cargo-Net analogy. I fixed the memory leak and added a '\0' to the string before the return. checked it in valgrind and it came back clean. Thanks for the reminder. I'm still learning. – Jack Galt Feb 29 '16 at 06:09
  • @UmamaheshP Thanks for the example. That works! And with much less code and no need for a function or a loop. That's what I was looking for. – Jack Galt Feb 29 '16 at 06:10

1 Answers1

2

Credit for this answer goes to UmamaheshP for pointing me in the right direction with a comment. This is what I was looking for and was adapted from an example he linked to.

#include <stdio.h>
#include <string.h>

int main (int argc, char *argv[]) {
    int i;
    char *pad = "________________";
    for (i = 1; i < argc; i++)
        printf ("%.*s\n%.*s%c %s\n", strlen(argv[i]), 
            pad,strlen(argv[i]), pad, '|', argv[i]);
}
Jack Galt
  • 83
  • 8