Home > database >  How to print two values in 2 different lines one above other?
How to print two values in 2 different lines one above other?

Time:12-28

I'm trying to print two values one above other. The two values are in two lines. How can I print them one above other without using spaces? I want to make sure that the 27 will be above the 26 in the same column.

#include<stdio.h>

void main() {
    printf("date:       27.12.2021\n");
    printf("date :       26.12.2021");
}

CodePudding user response:

You can use %s with a width specifier.

Like

#include <stdio.h>

int main() {
    printf("%-10s0s\n", "date:", "27.12.2021");
    printf("%-10s0s\n", "date :", "26.12.2021");
    
    return 0;
}

Output:

date:                         27.12.2021
date :                        26.12.2021

%-10s means: The string to be printed will be appended with spaces so that it has the width 10. In other words, the string will be printed left justified in a 10 character width field.

0s means: The string will be prepended with spaces so that it has the width 30. In other words, the string will be printed rigth justified in a 30 character width field.

Should the width of the original string already be the specified width (or more) no extra spaces will be added.

To really see how this works you can add | between the two fields like:

#include <stdio.h>

int main()
{

    printf("|%-10s|0s|\n", "date:", "27.12.2021");
    printf("|%-10s|0s|\n", "date :", "26.12.2021");

    return 0;
}

Output:

|date:     |                    27.12.2021|
|date :    |                    26.12.2021|

CodePudding user response:

For example you can write

printf( "date: s\n", "27.12.2021" );
printf( "date: s\n", "26.12.2021" );

or

printf( "date: %*s\n", 16, "27.12.2021" );
printf( "date: %*s\n", 16, "26.12.2021" );

In the both cases the output is

date:       27.12.2021
date:       26.12.2021

If the space between the word date and the semicolon in the second line is not a typo then you can write

printf( "date: %*s\n", 16, "27.12.2021" );
printf( "date : %*s\n", 15, "26.12.2021" );

CodePudding user response:

\t would give exactly three spaces.

void main()
{
    printf("date:\t27.12.2021\n");
    printf("date:\t26.12.2021");            
}
  • Related