Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,624 questions

56,911 answers

573 users

How to format a string using fixed-width fields in C

3 Answers

0 votes
#include <stdio.h>

/*
Common format specifiers
------------------------------------
%-10s // Left-aligned string, width 10
%10s // Right-aligned string, width 10
%5d // Integer, width 5
%08d // Integer, width 8, padded with zeros
%12.2f // Float, width 12, 2 decimal places
*/

// Formats a record using fixed-width fields
void formatRecord(char *output, size_t size,
                  const char *name,
                  int age,
                  double salary)
{
    /*
     * %-15s : string, left-aligned, width 15
     * %10d  : integer, right-aligned, width 10
     * %12.2f: floating-point, width 12, 2 decimal places
     */
    snprintf(output, size,
             "%-15s%10d%12.2f",
             name, age, salary);
}

int main(void)
{
    char result[64] = "";

    // Store the formatted string in result
    formatRecord(result, sizeof(result),
                 "Luna", 30, 85000.0);

    printf("%s\n", result);

    return 0;
}



/*
run:

Luna                   30    85000.00

*/

 



answered 4 days ago by avibootz
0 votes
#include <stdio.h>

int main(void)
{
    char result[32] = "";

    // Store "Hello" in a field 10 characters wide
    snprintf(result, sizeof(result), "%-10s", "Hello");

    printf("|%s|\n", result);

    return 0;
}


/*
run:

|Hello     |

*/

 



answered 4 days ago by avibootz
0 votes
#include <stdio.h>

int main(void)
{
    char result[32] = "";

    snprintf(result, sizeof(result), "%08d", 123);

    printf("%s\n", result);

    return 0;
}


/*
run:

00000123

*/

 



answered 4 days ago by avibootz
...