Print one neatly aligned line of a receipt.
What to build
A program that reads three types of value, and prints them in fixed columns.
Requirements
- Read an item name, a quantity and a unit price.
- Print the name left-aligned in 8 characters, a space, the quantity right-aligned in 5, a space, and the total cost right-aligned in 8 with two decimals.
Input
One line: the name, the quantity and the price.
Output
One line.
Constraints
The name has at most 8 letters. The quantity is from 0 to 9999 and the price from 0 to 999.
Example
Input:
Rice 2 65.5
Output:
Rice 2 131.00
Why it works
Fixed widths make every line take up the same space, so that columns line up when several lines are printed.
Examples
Example 1 · Input
Rice 2 65.5
Expected output
Rice 2 131.00
Example 2 · Input
Oil 1 180
Expected output
Oil 1 180.00
Hints
Hint 1
Use %s for the name, %d for the quantity and %lf for the price.
Hint 2
%-8s pads on the right, and %8.2f pads on the left.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int main(void) {
char name[20];
int qty;
double price;
scanf("%19s %d %lf", name, &qty, &price);
printf("%-8s %5d %8.2f\n", name, qty, qty * price);
return 0;
}