Help
Help

Reputation: 25

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

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)?

Upvotes: 0

Views: 1153

Answers (4)

chux
chux

Reputation: 153498

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
}

Upvotes: 0

Rinkesh P
Rinkesh P

Reputation: 678

#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

Upvotes: 0

Ayyjayy2
Ayyjayy2

Reputation: 31

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.

Upvotes: 0

Barmar
Barmar

Reputation: 781058

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);

Upvotes: 2

Related Questions