1. Goals
Combine variables, conditions, loops, functions, and strings in a small program.
Read a name, quantity, and unit price; print the discounted total.
Try valid, invalid, boundary, and end-of-input cases.
2. Prerequisites
Complete the first six lessons of stage 1, especially passing by value and
std::getline. This concludes the introductory stage; it is not the final
book-management project for all of Foundation. You do not need custom
classes, vector, or file input and output yet.
3. Explanation
Requirements: the customer name must not be empty; quantity is 1–20;
unit price is 1000–1000000 Vietnamese dong. Buying at least 5 items
earns a 10% discount. Print the subtotal, discount, and amount to pay.
Enter each number on its own line.
Money uses long long, an integer type with at least 64 bits. No double
is needed because the unit is one dong. The discount is
subtotal * 10 / 100; integer division discards the fractional part, which
rounds down for the positive values here. A subtotal of 5005 gets a
discount of 500, leaving 4505. The input bounds limit the subtotal to
20000000 and the intermediate product to 200000000, both within the
range of long long.
subtotalFor and discountFor only calculate from their parameters, passed
by value. They do not read the keyboard, so you can try them with specific
numbers. main connects the steps: read, validate, calculate, print.
readNumber uses one new tool from <sstream>:
std::istringstream input(line) creates an input stream from the string
line rather than the keyboard. input >> value works like std::cin >> value.
After reading a number, input >> extra tries to read another word; success
means there is unwanted data. This rejects 2abc, 2.5, and 2 3, while
allowing trailing whitespace.
The || condition stops at its first true operand. If a number could not
be read, there is no need to check leftovers. For invalid input, continue
starts another loop iteration. Each attempt creates a fresh string stream,
so a previous parsing failure cannot poison the next attempt. std::cin
only uses getline; the two input styles are not mixed.
When getline can no longer read, readNumber returns -1. This lies
outside every accepted range in this program and tells main to stop
without printing a receipt. EOF is not invalid input to retry indefinitely.
Exit status 0 here means a normal finish, including the user ending
input partway through.
4. Runnable example
Save as main.cpp and compile with C++17.
#include <iostream>
#include <sstream>
#include <string>
long long readNumber(std::string prompt, long long minimum, long long maximum) {
while (true) {
std::cout << prompt << '\n';
std::string line;
if (!std::getline(std::cin, line)) {
return -1;
}
std::istringstream input(line);
long long value = 0;
std::string extra;
if (!(input >> value) || (input >> extra) ||
value < minimum || value > maximum) {
std::cout << "Enter one integer in the allowed range.\n";
continue;
}
return value;
}
}
long long subtotalFor(long long quantity, long long unitPrice) {
return quantity * unitPrice;
}
long long discountFor(long long subtotal, long long quantity) {
if (quantity >= 5) {
return subtotal * 10 / 100;
}
return 0;
}
int main() {
std::cout << "Customer:\n";
std::string customer;
if (!std::getline(std::cin, customer)) {
return 0;
}
if (customer.empty()) {
std::cout << "Name is required.\n";
return 1;
}
long long quantity = readNumber("Quantity (1-20):", 1, 20);
if (quantity == -1) {
return 0;
}
long long unitPrice = readNumber("Unit price (1000-1000000):", 1000, 1000000);
if (unitPrice == -1) {
return 0;
}
long long subtotal = subtotalFor(quantity, unitPrice);
long long discount = discountFor(subtotal, quantity);
std::cout << "Receipt for " << customer << '\n';
std::cout << "Subtotal: " << subtotal << '\n';
std::cout << "Discount: " << discount << '\n';
std::cout << "Total: " << subtotal - discount << '\n';
return 0;
}Enter these three lines, pressing Enter after each:
Mai Nguyen
5
1001Program output, excluding input echoed by the terminal:
Customer:
Quantity (1-20):
Unit price (1000-1000000):
Receipt for Mai Nguyen
Subtotal: 5005
Discount: 500
Total: 45055. Common mistakes
Using
quantity > 5, so five items miss the discount: the rule is>= 5.Writing
subtotal * (10 / 100): integer division makes10 / 100zero.Accepting
2abcas quantity2by forgetting to check the rest of the line.Changing only the result type while still multiplying in a smaller type.
Mistaking
empty()for a meaningful-name check: a spaces-only name is not empty.Continuing the loop at EOF: there is no new line to read.
6. Practice
Rebuild the program before consulting the solution. It is complete when names retain internal spaces, bad numbers prompt again, only a full line containing one valid integer is accepted, and EOF always stops without printing a receipt from incomplete data.
Try
1item at1000: subtotal1000, discount0. Try20items at1000000: subtotal20000000, discount2000000, payable18000000.Try quantities
4and5, both at1000: payable amounts are4000and4500. Try quantities0,21, an empty line,abc,2abc,2.5,2 3, and an excessively long number; each must report an error and prompt again. Also try unit prices999and1000001.End input immediately, after the name, then after the quantity. Every case must stop without a
Receipt forline. An empty name line must report the name error.Extend it: reject names containing only whitespace, then allow up to three receipts. Keep calculation functions separate from input and output, and recheck the cases above.
7. Self-check
Why does using
-1to stop input not discard a valid quantity? Answer: quantities are restricted to1–20; unit prices are also positive.Why does an invalid line not make the next numeric read fail automatically? Answer: each attempt reads a new line and creates a new
istringstream; the old string stream's error state is not reused.What should
5items at1001cost, and why? Answer:4505: subtotal5005, discount500after discarding the fractional part of5005 * 10 / 100. This is the chosen rounding rule, not a floating-point error.
Sample code
Source file
cpp98_foundation/07_stage1_practice/main.cpp
#include <iostream>
#include <sstream>
#include <string>
long long readNumber(std::string prompt, long long minimum, long long maximum) {
while (true) {
std::cout << prompt << '\n';
std::string line;
if (!std::getline(std::cin, line)) {
return -1;
}
std::istringstream input(line);
long long value = 0;
std::string extra;
if (!(input >> value) || (input >> extra) ||
value < minimum || value > maximum) {
std::cout << "Enter one integer in the allowed range.\n";
continue;
}
return value;
}
}
long long subtotalFor(long long quantity, long long unitPrice) {
return quantity * unitPrice;
}
long long discountFor(long long subtotal, long long quantity) {
if (quantity >= 5) {
return subtotal * 10 / 100;
}
return 0;
}
int main() {
std::cout << "Customer:\n";
std::string customer;
if (!std::getline(std::cin, customer)) {
return 0;
}
if (customer.empty()) {
std::cout << "Name is required.\n";
return 1;
}
long long quantity = readNumber("Quantity (1-20):", 1, 20);
if (quantity == -1) {
return 0;
}
long long unitPrice = readNumber("Unit price (1000-1000000):", 1000, 1000000);
if (unitPrice == -1) {
return 0;
}
long long subtotal = subtotalFor(quantity, unitPrice);
long long discount = discountFor(subtotal, quantity);
std::cout << "Receipt for " << customer << '\n';
std::cout << "Subtotal: " << subtotal << '\n';
std::cout << "Discount: " << discount << '\n';
std::cout << "Total: " << subtotal - discount << '\n';
return 0;
}