简体   繁体   中英

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

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

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.

#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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM