Use streams and check extraction
A small C++ console program includes the headers for the facilities it uses, defines main, reads values and reports a result. Input streams maintain a state that records whether an extraction succeeded. Never calculate with input that failed validation.
Worked program: total lesson time
#include
int main() {
int lessons = 0;
int minutes = 0;
std::cout << "Enter lesson count and minutes each: ";
if (!(std::cin >> lessons >> minutes)) {
std::cerr << "Expected two integers.\n";
return 1;
}
if (lessons < 1 || lessons > 100 || minutes < 1 || minutes > 180) {
std::cerr << "Values are outside the permitted range.\n";
return 1;
}
std::cout << "Total minutes: " << lessons * minutes << '\n';
} Input 4 30 produces Total minutes: 120. Input four 30 reports an extraction error. The range checks also keep multiplication small enough for the integer type. Reaching the end of main is equivalent to returning zero.
Strings containing spaces
std::cin >> name reads a whitespace-delimited word. std::getline(std::cin, name) reads a line and discards its delimiter. Mixing formatted extraction with getline often leaves the previous newline waiting in the stream. Handle that boundary deliberately.
#include
#include
// After a successful numeric extraction:
std::cin.ignore(std::numeric_limits::max(), '\n');
std::string full_name;
if (!std::getline(std::cin, full_name)) {
// Handle end-of-file or an input error.
} These are fragments to place inside a function with iostream included. ignore discards the remainder of the current line. Alternatively, read complete lines throughout and parse each line separately.
Recovering a failed stream
After a recoverable format failure in an interactive loop, clear the failure state, then discard the invalid line. Calling clear alone does not remove the bad input. End-of-file should normally end the loop instead of repeatedly prompting forever.
Output choices
Use cout for normal results and cerr for diagnostic messages. A newline character ends a line; std::endl also flushes the stream. Flushing every iteration can add unnecessary overhead. Include iomanip when formatting decimal precision with std::fixed and std::setprecision.
Practice
- Read a student's full name and print a greeting without losing spaces.
- Test empty input, letters where numbers are required, and the maximum permitted values.
- Why is extracting an int from the string "3.5" not enough to validate the entire line? It can consume the integer prefix and leave trailing characters; full-line validation needs additional checks.