Awesome
correct_cpp_is_odd
Branch | Travis CI | Codecov |
---|---|---|
master |
Correct C++ chapter 'is odd'.
Goals
- Respond to exceptions
Prerequisites
- Understand how this course works
- Have written a correct 'Show CLI arguments' program
Exercise
Write a command-line interface (CLI) program that determines if its argument is an odd number.
If there are more arguments supplied, ignore the ones beyond the first
Call to is_odd | Output | Exit status |
---|---|---|
./is_odd | Any | 1 |
./is_odd 1 | true (with newline) | 0 |
./is_odd 2 | false (with newline) | 0 |
./is_odd nonsense | Any | 1 |
./is_odd 12345678901234567890 | Any | 1 |
./is_odd 2 1 | false (with newline) | 0 |
With 'Any' output, you can choose to:
- inform the user, for example: 'Error: must supply one argument'
- give no ouput at all: the exit status of 1 indicates that the program ended with an error
This is the code you start with:
main(argc, argv)
{
//Your code here
}
- Use std::stoi to convert a std::string to an int
- std::stoi properly [2] throws an exception if the std::string cannot be converted to an integer:
- when the std::string is a word, like
nonsense
- when the std::string is a number too big to be an integer, like
12345678901234567890
- when the std::string is a word, like
- Use try and catch to respond to the exception thrown by std::stoi
- Avoid std::endl [1]
- catch the exception by reference [3]
- You can have multiple catch clauses per try
- Use const to define objects with values that do not change after construction [4]
External links
References
- [1] C++ Core Guidelines: SL.io.50: Avoid endl
- [2] C++ Core Guidelines: E.2: Throw an exception to signal that a function can't perform its assigned task
- [3] C++ Core Guidelines: E.15: Catch exceptions from a hierarchy by reference
- [4] C++ Core Guidelines: Con.4: Use const to define objects with values that do not change after construction