Learn / Worked program
Wood Movement Teaching Model
Lookup tables need unit semantics and evidence labels
What you will learn
- Console streams and complete-line input/outputProgram-local teaching concept
- Finite double arithmetic, precision and round-offValues and typesProgram-local teaching concept
- Branch order, validated domains and early returnsLearn conceptDecisions and repetition
- Physical quantities, conversions and dimensionally consistent modelsProgram-local teaching concept
- Named value records and grouped stateLearn conceptRecords, enumerations, and classes
- Fixed-size collections, initialized elements and indexed accessLearn conceptArrays and strings
- Aliases for mutable or read-only existing objectsLearn conceptPointers and references
- Complete-line parsing, bounded input and EOF terminationDebugging and code qualityProgram-local teaching concept
- Zero-based indices and checked accessLearn conceptArrays and strings
The complete source
main.cpp
#include <array>
#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;
}
bool readInteger(const std::string& prompt, int& value, int low, int 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) && value >= low && value <= high) return true;
std::cout << "Enter a whole number in [" << low << ", " << high << "].\n";
}
std::cerr << "Input ended before a valid integer was supplied.\n";
return false;
}
struct Wood {
const char* name;
double quarterCoefficient;
double flatCoefficient;
};
int main() {
// Historical assignment coefficients, per moisture percentage POINT.
// Their physical calibration is unverified; this is a teaching model.
const std::array<Wood, 4> woods{{
{"Alder", 0.0015, 0.0026}, {"Cherry", 0.0013, 0.0025},
{"Red Oak", 0.0016, 0.0037}, {"Black Walnut", 0.0019, 0.0027}
}};
double widthInches = 0.0, moisturePoints = 0.0;
if (!readNumber("Initial width (inches): ", widthInches, 1e-6, 1e4)
|| !readNumber("Signed moisture change (percentage points): ", moisturePoints, -30.0, 30.0)) return 1;
for (std::size_t i = 0; i < woods.size(); ++i) std::cout << i + 1 << ". " << woods[i].name << '\n';
int woodChoice = 0, cutChoice = 0;
if (!readInteger("Wood (1 to 4; 0 exits): ", woodChoice, 0, 4)) return 1;
if (woodChoice == 0) return 0;
if (!readInteger("Cut (1 quarter, 2 flat; 0 exits): ", cutChoice, 0, 2)) return 1;
if (cutChoice == 0) return 0;
const Wood& wood = woods.at(static_cast<std::size_t>(woodChoice - 1));
const double coefficient = cutChoice == 1 ? wood.quarterCoefficient : wood.flatCoefficient;
const double change = widthInches * moisturePoints * coefficient;
std::cout << std::fixed << std::setprecision(6)
<< "Teaching model; historical coefficients not independently calibrated.\n"
<< "Width change (in): " << change << '\n'
<< "New width (in): " << widthInches + change << '\n';
}
Source integrity
SHA-256 39bb7a0d0a62b8c2ad4d1538d76fe89e316ba81ee3993f7dc0b40fffe4be7a68. Display, copy and approved download use the same source.
What it does and why it was selected
The wood lab naturally combines materials choices, bounded menus, tabulated coefficients and a physical output. It is also a useful lesson in provenance: executing an equation correctly does not establish that the historical coefficients have been independently calibrated for a real project. That limitation is visible in the canonical output.
Actual execution
main creates a fixed array of four Wood records. Each record binds a name to its quartersawn and flatsawn coefficients, preventing parallel tables from becoming misaligned. Width is entered first, followed by signed moisture-content change. The loop prints the menu from the same array used in the calculation. A zero choice exits deliberately. The validated one-based wood selection is converted to a zero-based index and accessed with at. A const reference binds to the chosen record without copying or allowing mutation. Cut selection chooses one coefficient; multiplication gives width change, and addition gives new width.
Mathematical or state model
The retained assignment model is deltaW=WdeltaMCk. W and deltaW are inches. deltaMC is a change in moisture CONTENT expressed in percentage points, not relative humidity and not a decimal fraction. Thus changing moisture content from 8% to 12% means deltaMC=4, not 0.04. k is used per percentage point. The sample 10-inch quartersawn cherry board with a +4-point change uses k=0.0013, producing +0.052 inch and final width 10.052. A -4-point change gives -0.052, representing contraction.
Design and C++ mechanics
A record makes the coefficient relationship explicit instead of relying on the reader to remember that index 1 means cherry in both independent vectors. Menu validation proves that woodChoice-1 is 0..3 before conversion to size_t. at adds a checked access boundary, although a programming mistake outside those bounds should still be fixed. The ternary coefficient selection is safe because the cut is already known to be either 1 or 2. Passing the selected Wood as a const reference expresses observation rather than ownership transfer.
Historical differences and limits
The coefficients come from the historical lab and have no cited calibration source in the archive. They are deliberately labeled unverified historical teaching values. The program neither certifies joinery tolerances nor predicts arbitrary moisture ranges. Real wood movement depends on species, grain orientation, initial/final moisture content and conditions; the simple linear approximation and menu labels omit much of that. Input bounds keep outputs finite and widths positive in this teaching domain, but bounds do not validate the physical coefficient model.
Useful extensions
Replace coefficients only after attaching an authoritative source and clearly defining how values were derived and which moisture interval they describe. A future version could distinguish radial/tangential directions from practical sawing approximations. Keep the historical values available as provenance, so users can tell when a change improves physical evidence rather than merely changes C++ syntax.
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 Wood Movement Teaching Model 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 contract and end-of-file
main.cpp, lines 24–34 →Only validated whole integers are allowed to reach the Wood Movement Teaching Model 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.
Bind identity to coefficient evidence
main.cpp, lines 36–40 →A Wood record owns neither dynamic strings nor heap storage: name points at a static string literal, and the two doubles store historical coefficients.
- Technical explanation
- A Wood record owns neither dynamic strings nor heap storage: name points at a static string literal, and the two doubles store historical coefficients. The pair’s meaning remains attached to its material name. This is a data grouping rather than a class enforcing calibration validity.
- Syntax
- This is a data grouping rather than a class enforcing calibration validity.
- Effect on the program
- This is a data grouping rather than a class enforcing calibration validity.
- Common mistake
- Parallel vectors require every index to stay synchronized. Grouping values helps association but does not verify physical data.
- Deeper connection
- Read the program’s mathematical or state model
Fixed historical lookup data
main.cpp, lines 45–49 →The array has exactly four records initialized in menu order.
- Technical explanation
- The array has exactly four records initialized in menu order. Braces construct each record, with quarter coefficient before flat coefficient. const prevents editing coefficients during a run. The nearby source comment explicitly labels them as historical assignment values per percentage point.
- Syntax
- The nearby source comment explicitly labels them as historical assignment values per percentage point.
- Effect on the program
- The nearby source comment explicitly labels them as historical assignment values per percentage point.
- Common mistake
- A bare coefficient without source or unit semantics can look authoritative despite being unverified.
- Deeper connection
- Read the program’s mathematical or state model
One-based menu to checked zero-based access
main.cpp, lines 58–65 →After woodChoice is proven to be 1..4, subtracting one yields 0..3.
- Technical explanation
- After woodChoice is proven to be 1..4, subtracting one yields 0..3. at checks that index, and const Wood& aliases the existing record read-only. The cut choice selects one coefficient. width*moisturePoints*coefficient gives signed change, which is then added to the initial width.
- Syntax
- width*moisturePoints*coefficient gives signed change, which is then added to the initial width.
- Effect on the program
- width*moisturePoints*coefficient gives signed change, which is then added to the initial width.
- Common mistake
- A +4 percentage-point moisture change is 4 here, not 0.04 and not 4% relative humidity.
- Deeper connection
- Read the program’s mathematical or state model
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
10 4 2 1
Program output
Initial width (inches): Signed moisture change (percentage points): 1. Alder 2. Cherry 3. Red Oak 4. Black Walnut Wood (1 to 4; 0 exits): Cut (1 quarter, 2 flat; 0 exits): Teaching model; historical coefficients not independently calibrated. Width change (in): 0.052000 New width (in): 10.052000
5 more recorded behavior and error cases
contraction
- Arguments
None- Recorded exit status
- 0
Program input
10 -4 2 1
Program output
Initial width (inches): Signed moisture change (percentage points): 1. Alder 2. Cherry 3. Red Oak 4. Black Walnut Wood (1 to 4; 0 exits): Cut (1 quarter, 2 flat; 0 exits): Teaching model; historical coefficients not independently calibrated. Width change (in): -0.052000 New width (in): 9.948000
red oak flat
- Arguments
None- Recorded exit status
- 0
Program input
10 4 3 2
Program output
Initial width (inches): Signed moisture change (percentage points): 1. Alder 2. Cherry 3. Red Oak 4. Black Walnut Wood (1 to 4; 0 exits): Cut (1 quarter, 2 flat; 0 exits): Teaching model; historical coefficients not independently calibrated. Width change (in): 0.148000 New width (in): 10.148000
exit
- Arguments
None- Recorded exit status
- 0
Program input
10 4 0
Program output
Initial width (inches): Signed moisture change (percentage points): 1. Alder 2. Cherry 3. Red Oak 4. Black Walnut Wood (1 to 4; 0 exits):
bad choice
- Arguments
None- Recorded exit status
- 0
Program input
10 4 9 2 1
Program output
Initial width (inches): Signed moisture change (percentage points): 1. Alder 2. Cherry 3. Red Oak 4. Black Walnut Wood (1 to 4; 0 exits): Enter a whole number in [0, 4]. Wood (1 to 4; 0 exits): Cut (1 quarter, 2 flat; 0 exits): Teaching model; historical coefficients not independently calibrated. Width change (in): 0.052000 New width (in): 10.052000
eof
- Arguments
None- Recorded exit status
- 1
Program input
No standard input.
Program output
Initial width (inches):
Error output
Input ended before a valid number was supplied.
Build and run
From this folder, with a configured C++17 compiler:
g++ -std=c++17 -Wall -Wextra -Wpedantic main.cpp -o program
./programOn 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: 6 recorded behavior/error cases and 6 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.