Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print trailing spaces in C

Tags:

c

printf

I want to print some data like this:

John       22
Shakib     25
Ponting    28

Here i need to print some trailing spaces after the name.

I did this following way:

char *name[]={"John", "Shakib", "Ponting"};
int age[]={22, 25, 28};
int n=3;
for(int i=0; i<n; i++)
{
    printf("%s",name[i]);
    int cnt=10;  // I need trailing spaces upto 10th column
    int len=strlen(name[i]);
    cnt-=len;
    while(cnt)
    {
        printf(" ");
        cnt--;
    }
    printf("%d\n",age[i]);
}

Is there any other way to print trailing spaces without using loop?

like image 848
Isco Avatar asked Dec 09 '22 04:12

Isco


1 Answers

To print trailing spaces you can use either

for(int i = 0; i < n; i++)
  printf("%-10s%d\n", name[i], age[i]);

or

int cnt = 10;
for(int i = 0; i < n; i++)
  printf("%-*s%d\n", cnt, name[i], age[i]);
like image 139
Ali Akber Avatar answered Dec 15 '22 01:12

Ali Akber