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 Oct 17 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 Oct 17 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 Oct 17 by avibootz
...