Home > Blockchain >  How to print an int and a string with spaces after using printf?
How to print an int and a string with spaces after using printf?

Time:12-16

I usually use printf("%-8d",a); for example for 8 spaces after (and including) an integer. My code:

#include <stdio.h>
#include <string.h>
    
int main()
{
    int a = 10;
    char b = "Hello";
}

How can I print: '#10-Hello ' with 16 spaces (8 is the integer and the string, and 8 spaces after)?

CodePudding user response:

Do it in two steps. First combine the number and string with sprintf(), then print that resulting string in a 16-character field.

int a = 10;
char *b = "Hello";
char temp[20];
sprintf(temp, "#%d-%s", a, b);
printf("%-16s", temp);

CodePudding user response:

A tab is 8 spaces, so, you can add \t\t The below is a super basic way to print what you wanted.

printf('#'   a   '-'   b   '\t\t');

I'm not as familiar with the syntax of C so it may be :

printf('#', a, '-', b, '\t\t');

Also, as mentioned in a previous answer, "Hello" is not a char but either an array of char or a String.

CodePudding user response:

#include <stdio.h>
#include <string.h>
    
int main()
{
    int a = 10;
    char b[] = "Hello";
    printf("#%d-%-17s",a,b);
}

this should get the job done, adjust your spacing as needed

CodePudding user response:

Could do this with 2 printf()s. Use the return value of the first to know its print length, then print spaces needed to form a width of 16. No temporary buffer needed.

#include <assert.h>
#include <stdio.h>

int main(void) {
    int width = 16;
    int a = 10;
    char *b = "Hello"; // Use char *

    int len = printf("#%d-%s", a, b);
    assert(len <= width && len >= 0);
    printf("%*s", width - len, "");  // Print spaces
}
  • Related