Site Guide

Find your way around the Engineering Club.

Know what you need? Search for a component, concept or project.

Around the site

Start

Labs

TestingExperimental

Build

Club

LearnExperimental

Go a little deeper

Entry points to larger collections. Use Search for individual records.

Learning paths & reference

Inside PiCrawlerExperimental

Inside Inventory

← C++ Worked Programs

Learn / Worked program

Temperature Converter

Units, return objects and a physical boundary

BeginnerDesktop C++17 · runnable source

What you will learn

The complete source

main.cpp

main.cpp
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

// Read one whole line so a failed conversion cannot trap the input stream.
bool readNumber(const std::string& prompt, double& value, double low, double high) {
    std::string line;
    while (std::cout << prompt && std::getline(std::cin, line)) {
        std::istringstream input(line);
        char extra = '\0';
        if (input >> value && !(input >> extra) && std::isfinite(value)
            && value >= low && value <= high) {
            return true;
        }
        std::cout << "Enter a finite number in [" << low << ", " << high << "].\n";
    }
    std::cerr << "Input ended before a valid number was supplied.\n";
    return false;
}

struct Temperatures {
    double celsius;
    double kelvin;
};

Temperatures convertFromFahrenheit(double fahrenheit) {
    const double celsius = (fahrenheit - 32.0) * (5.0 / 9.0);
    // Round-off at the absolute-zero boundary must not print negative Kelvin.
    return {celsius, std::max(0.0, celsius + 273.15)};
}

int main() {
    double fahrenheit = 0.0;
    if (!readNumber("Temperature in F: ", fahrenheit, -459.67, 1e6)) return 1;
    const Temperatures result = convertFromFahrenheit(fahrenheit);
    std::cout << std::fixed << std::setprecision(3)
              << "Celsius: " << result.celsius << '\n'
              << "Kelvin: " << result.kelvin << '\n';
}
Source integrity

SHA-256 785fd009d878b58edbe37ed44cc37f929eaa7879c87453119e54a00b0fc2871d. Display, copy and approved download use the same source.

What it does and why it was selected

This is a small engineering program with a defensible model and an obvious validation boundary. It keeps the historical lab’s Fahrenheit-to-Celsius-and-Kelvin task while introducing a compact returned struct rather than several unrelated output variables.

Actual execution

The input helper accepts Fahrenheit from -459.67 to the teaching limit 1e6. main calls convertFromFahrenheit exactly once. Inside that function, the Fahrenheit offset is removed before multiplication by 5.0/9.0; adding 273.15 then changes the Celsius origin to the Kelvin origin. Aggregate initialization constructs a Temperatures value containing both answers. main owns that returned value and prints its two named fields. For 32 F, the actual transcript contains 0.000 C and 273.150 K; 212 F produces 100.000 C and 373.150 K.

Mathematical or state model

C=(F-32)*(5/9), K=C+273.15. These are transformations of a temperature reading, not the formula for a temperature difference. A difference of 32 F is not a difference of zero C; differences use scale factors without origin offsets. The lower Fahrenheit threshold corresponds to zero kelvin. The teaching range and formatting are interface choices, not a promise that all extreme temperatures describe ordinary materials.

Design and C++ mechanics

The conversion function has no input/output side effects. Its parameters are passed by value, and the returned struct groups results from one input. This matters if a future application wants to plot temperatures or compare sensors: it can call the conversion without scraping console text. Explicit floating literals avoid integer division. The use of std::fixed makes setprecision(3) mean three fractional digits rather than three significant digits.

Historical differences and limits

Floating-point evaluation at the absolute-zero boundary can leave a tiny negative Kelvin result. std::max clamps that rounding artifact to zero after the input domain has been validated. It would be incorrect to use this clamp to hide substantially invalid input: the readNumber lower bound handles that separately. The historical lab’s numeric formula was already correct; modernization mainly adds reliable input failure handling and a meaningful returned record.

Useful extensions

Add Celsius or Kelvin as alternative input scales with clearly named functions. A good test checks that round trips recover the original value within a justified tolerance. Keep reading temperatures and converting differences separate, and explain any changed rounding policy before displaying more precision.

Source-linked explanations

Follow each line reference to its marked source region. The explanations below are bound to the reviewed source hash and preserve the supplied teaching layers.

Input contract and end-of-file

main.cpp, lines 9–22 →

Only validated finite numbers are allowed to reach the Temperature Converter calculation.

Technical explanation
getline consumes a complete line, then a temporary istringstream attempts the numeric conversion. After conversion, trying to extract extra detects a trailing non-whitespace character. Failure of that second extraction means no unwanted data remains. The local stream can fail without putting cin into the historical repeated-failbit state. A fresh local stream is created for every attempt. Low/high comparisons establish the caller’s domain, and exhausting cin ends the while condition and returns false.
Syntax
The && operators evaluate left to right and short-circuit: range tests run only after numeric extraction succeeds. !(input >> extra) intentionally treats no remaining non-whitespace character as success. A double& or int& parameter writes the accepted value into the caller’s variable.
Effect on the program
The caller checks the returned bool and returns exit status 1 on EOF before calculation. Rejected lines are followed by another prompt; valid lines reach the model exactly once.
Common mistake
Clearing a permanently exhausted input stream and retrying cannot create new input. Accepting a numeric prefix such as 550x would silently change the input contract.
Deeper connection
Reliable input separates parsing from physical or algorithmic validity: a valid number still must lie in this program’s supported domain.

input validationconsole ioreferences

Group related results

main.cpp, lines 24–27 →

Two named double fields describe one conversion result.

Technical explanation
Two named double fields describe one conversion result. They are stored by value in the returned object, so main can independently read celsius and kelvin. No dynamically allocated object or pointer ownership is introduced by this struct.
Syntax
No dynamically allocated object or pointer ownership is introduced by this struct.
Effect on the program
No dynamically allocated object or pointer ownership is introduced by this struct.
Common mistake
A struct does not automatically validate physical temperatures. Its consistency depends on the function that creates it.

structsfloating point

Scale and offset in the right order

main.cpp, lines 29–33 →

Subtracting 32 moves the Fahrenheit zero before multiplying by 5.0/9.0 changes its degree size.

Technical explanation
Subtracting 32 moves the Fahrenheit zero before multiplying by 5.0/9.0 changes its degree size. Both literals are floating-point, so division yields a fractional ratio. The braced return initializes celsius first and Kelvin second in declaration order. std::max only trims a tiny negative Kelvin rounding artifact at the already-validated boundary.
Syntax
std::max only trims a tiny negative Kelvin rounding artifact at the already-validated boundary.
Effect on the program
std::max only trims a tiny negative Kelvin rounding artifact at the already-validated boundary.
Common mistake
Writing 5/9 with integer operands produces zero. Clamping arbitrary invalid temperatures instead of rejecting them hides a different error.

functionsfloating pointstructs

Consume one coherent return value

main.cpp, lines 38–42 →

main obtains both outputs from one call and then only observes the const result.

Technical explanation
main obtains both outputs from one call and then only observes the const result. This guarantees that displayed Celsius and Kelvin came from the same accepted Fahrenheit reading. Access through result.celsius selects a named field, not a function call.
Syntax
Access through result.celsius selects a named field, not a function call.
Effect on the program
Access through result.celsius selects a named field, not a function call.
Common mistake
Recalculating fields independently in output code makes it easier to use inconsistent inputs or constants.

functionsformatted output

Recorded input and output

Captured from the compiled canonical program in the supplied verification package. These are recorded terminal sessions, not an interactive browser runner.

Sample run

Arguments
None
Recorded exit status
0

Program input

32

Program output

Temperature in F: Celsius: 0.000
Kelvin: 273.150
4 more recorded behavior and error cases
boiling
Arguments
None
Recorded exit status
0

Program input

212

Program output

Temperature in F: Celsius: 100.000
Kelvin: 373.150
absolute zero
Arguments
None
Recorded exit status
0

Program input

-459.67

Program output

Temperature in F: Celsius: -273.150
Kelvin: 0.000
below zero recover
Arguments
None
Recorded exit status
0

Program input

-460
32

Program output

Temperature in F: Enter a finite number in [-459.67, 1e+06].
Temperature in F: Celsius: 0.000
Kelvin: 273.150
eof
Arguments
None
Recorded exit status
1

Program input

No standard input.

Program output

Temperature in F: 

Error output

Input ended before a valid number was supplied.

Build and run

From this folder, with a configured C++17 compiler:

sh
g++ -std=c++17 -Wall -Wextra -Wpedantic main.cpp -o program
./program

On Windows GCC, build with -o program.exe and use .\program.exe. These are desktop examples; VS Code is an editor, the compiler builds an executable, and the terminal runs it.

Windows run command from the supplied metadata: .\program.exe.

Desktop compiler setup and platform limits. How headers and translation units fit together.

Verification and provenance

  • Source inspected
  • Compile verified
  • Warning reviewed
  • Behavior verified
  • Sanitizer checked

Supplied evidence: 5 recorded behavior/error cases and 5 address/undefined-behavior sanitizer cases for this exact source. These are tested cases, not an exhaustive correctness claim.

Recorded compiler: g++ (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0.

LeakSanitizer: disabled because unavailable under runtime tracing. Windows/MSVC and macOS execution are not certified by this evidence.

Source origin and publication treatment

Modernized user supplied source

User-supplied origin; no independent authorship or license determination. Instructor code is not included.

New or rewritten source, limited sanitized historical excerpts when useful

No new license is asserted by this publication.