(Can't use space and can't use: if,switch,.....case) I have my code:
#include <stdio.h>
int main()
{
int dd, mm, yyyy;
printf("Podaj date (w formacie dd-mm-yyyy):");
scanf("%d-%d-%d", &dd, &mm, &yyyy);
printf("Day:d\nMonth:d\nYear:d\n",dd,mm,yyyy);
return 0;
}
And output looks like this:
Podaj date:06-08-0009
Day:06
Month:08
Year:0009
And how do it like this
Podaj date: 06-08-0009
Day: 06
Month: 08
Year: 0009
CodePudding user response:
You could give the fixed parts of the format string as arguments instead and decide on the width of each in the format string:
printf("%-11sd\n%-11sd\n%-9sd\n", "Day:", dd, "Month:", mm, "Year:", yyyy);
// ^^^ ^^^ ^^^
// | | "Year:"
// | "Month:"
// |
// "Day:" - left adjusted, 11 chars
Also, always check that scanf
succeeds:
if(scanf("%d-%d-%d", &dd, &mm, &yyyy) == 3) {
printf("%-11sd\n%-11sd\n%-9sd\n", "Day:", dd, "Month:", mm, "Year:", yyyy);
}
CodePudding user response:
void scanAndPrint(unsigned nspaces)
{
int dd, mm, yyyy;
printf("Podaj date (w formacie dd-mm-yyyy):");
scanf("%d-%d-%d", &dd, &mm, &yyyy);
printf("\nDay:%*sd\nMonth:%*sd\nYear:%*sd\n", nspaces - 2 - (int)sizeof("DAY"),"", dd,nspaces - 2 - (int)sizeof("MONTH"),"", mm,nspaces - 4 - (int)sizeof("YEAR"),"", yyyy);
}