Introduction
Converting to Roman numerals is easy; validating them is the real exercise. This converter rejects non-canonical forms such as IIII, VX or IC with one elegant trick: decode the numeral, re-encode the value, and require the two to match.
Problem statement
add X Y or sub X Y (Roman or decimal operands) print the result in Roman numerals when it is in range. Report rejected items and a final count.Objectives
- Use a lookup table of value/symbol pairs
- Apply the subtractive rule when decoding
- Validate by round-tripping a conversion
- Return 'maybe a value' with std::optional
Features
- Decimal → Roman with a breakdown (M + CM + XC + IV)
- Roman → decimal, case-insensitive
- Rejects non-canonical and out-of-range input
- Roman addition and subtraction
Concepts demonstrated
- Lookup tables
- Greedy algorithms
- std::optional
- Validation by round trip
- std::transform
System architecture
TABLE lists the 13 value/symbol pairs from 1000 down to 1, including subtractive pairs such as 900/CM. to_roman is greedy: it repeatedly takes the largest value that fits. from_roman upper-cases the text, sums the symbols (subtracting a symbol smaller than its right neighbour), then returns std::nullopt unless to_roman(total) reproduces the input exactly. parse accepts either form, so the arithmetic commands work with mixed operands.
Folder structure
Complete source code
Makefile
What each file does
- src/main.cpp
- The symbol table,
to_roman,from_roman(with round-trip validation),parse,explainand the line loop. - 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.
1994 2026 3999 4000 0 MCMXCIV mmxxvi XLII IIII VX IC MMMM hello add XIV 28 sub X XII add MMM M
Testing
- Compare
./app < tests/sample-input.txtwithtests/expected-output.txt. - 1994 ↔ MCMXCIV, 2026 ↔ MMXXVI and 3999 ↔ MMMCMXCIX are checked both ways.
- IIII, VX, IC and MMMM must all be rejected; so must 0 and 4000.
Common errors
"IIII" is accepted as 4
Summing symbols alone isn't enough; compare the numeral with to_roman(value).
std::out_of_range from std::stoi on a long number
Reject digit strings longer than four characters before calling stoi, as parse does.
Possible improvements
- Support the vinculum (overline) notation for numbers above 3999
- Add multiplication and integer division
- Convert dates such as 2026-11-27 into Roman form
Additional challenges
- 1Write from_roman without the round-trip check, using explicit rules.
- 2Print a table of 1–100 in five columns.
- 3Count how many numerals from 1 to 3999 contain each symbol.
Built and tested it yourself? Mark it to update your dashboard.