Introduction
A unit converter looks simple, but the way it is organised matters. This version keeps every conversion in one table that pairs a label with a function, so adding a new unit is a one-line change and the menu builds itself.
Problem statement
Objectives
- Store related data and behaviour in an array of structs
- Use function pointers to select an operation at run time
- Print aligned tables with field widths
- Validate menu and table input
Features
- Eight conversions between common units
- Single-value conversion with two-decimal output
- Conversion tables with a chosen start, step and number of rows
- Absolute-zero warning for Kelvin conversions
Concepts demonstrated
- Function pointers
- Array of structs
- Formatted output
- Menu-driven design
System architecture
Each Conversion struct holds a label, the source and target unit names and a pointer to a double (*)(double) function. CONVERSIONS[] is the single source of truth: print_menu lists it, the menu choice indexes it, and print_table calls c->convert for each row.
Folder structure
Complete source code
Makefile
What each file does
- src/main.c
- The conversion functions, the
CONVERSIONStable, the menu, single conversions andprint_table. - Makefile
- Build automation:
makebuilds./app,make testruns the sample session and compares it with the expected output,make cleanremoves build files.
How to run it
Build
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
1 37 3 -300 9 4 0 5 5 5 26.2 0
Testing
- Compare the scripted run with
tests/expected-output.txt(37 °C, −300 °C → Kelvin warning, a km→mi table, a marathon in km→mi). - Check known values: 100 °C = 212 °F, 1 mi = 1.61 km, 1 kg = 2.20 lb.
Common errors
warning: initialization of 'double (*)(double)' from incompatible pointer type
A conversion function must take exactly one double and return double.
Table rows show 0.00 for every value
Read start and step with %lf, not %f or %d.
Possible improvements
- Add currency conversion with rates read from a file
- Support conversions in both directions from a single table entry
- Group conversions into categories in the menu
Additional challenges
- 1Add volume units (litres, gallons) without changing any code except the table.
- 2Allow input such as
37Cor10kmand detect the unit automatically. - 3Print a two-column table converting in both directions.
Built and tested it yourself? Mark it to update your dashboard.