Is there any method for C language to control length of characters by using a variable?

Here is my code :

#include <stdio.h>
int main(void)
{
    printf("%220s\n", "Hello, beautiful world!");
    printf("%232s\n", "Hello, beautiful world!");
    printf("%333s\n", "Hello, beautiful world!");
    printf("%444s\n", "Hello, beautiful world!");
    printf("%555s\n", "Hello, beautiful world!");

    return 0;
}

It takes a lot of typing and may be full of mistakes.

I am thinking of using a variable to control how many spaces the string can take up.

The following code

 #include <stdio.h>
int main(void)
{

    int a[5] = {220, 232, 333, 444, 555};

    for (int i = 0; i < 5; i++)
        printf("%%ds\n", a[i], "Hello, beautiful world!");

    return 0;
}

does not seem to work I expected.

Where did I do wrong?

Is there any method for C language to control length of characters by using a variable ?

Upvotes: 1

Views: 106

Answers (1)

Umair
Umair

Reputation: 78

You can use the * specifier to specify the minimum field width. For information please read the Format of the format string section on the man page for printf

#include <stdio.h>
int main(void)
{
    int a[5] = {220, 232, 333, 444, 555};

    for (int i = 0; i < 5; i++)
        printf("%*s\n", a[i], "Hello, beautiful world!");

    return 0;
}

Upvotes: 2

Related Questions