0

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

6
  • 1
    char b = "Hello" is a syntactic error, use array of char instead Commented Dec 15, 2021 at 16:32
  • 1
    Please show exactly what you want to get as output. Commented Dec 15, 2021 at 16:33
  • @Gerhardh I fixed his formatting so it's clear what he wants Commented Dec 15, 2021 at 16:34
  • So, "spaces" does not mean spaces (' ') but any characters in the output. Commented Dec 15, 2021 at 16:36
  • 1
    He wants to print #a-b in a 16-character field with space padding. Commented Dec 15, 2021 at 16:37

4 Answers 4

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Perhaps snprintf() to ward off buffer overruns with updated code?
0

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.

Comments

0
#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

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.