cin
, assert
, and abort
Assertions and aborts are tools used to enforce program correctness and handle critical errors.
Assertions are used to verify assumptions made by the program. When an assertion fails, the program is immediately halted.
#include <cassert> // for assert
int testVowel()
{
#ifdef NDEBUG
// If NDEBUG is defined, asserts are compiled out.
// Since this function requires asserts to not be compiled out, we'll terminate the program if this function is called when NDEBUG is defined.
std::cerr << "Tests run with NDEBUG defined (asserts compiled out)";
std::abort();
#endif
assert(isLowerVowel('a'));
return 0;
}
The std::abort
function is used to terminate the program abnormally.
#include <cstdlib> // for std::abort
void terminateProgram()
{
std::cerr << "Critical error, aborting program.";
std::abort();
}
std::cerr
and std::exit
std::cerr
is used for error output and diagnostic information.
std::cout << "Error: Could not divide by zero\n";
std::exit(1);
cin
To ignore everything up to and including the next '\n'
character:
#include <limits> // for std::numeric_limits
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.eof()
: Returns true if the last input operation reached the end of the input stream.std::cin.peek()
: Allows peeking at the next character in the input stream without extracting it.If an extraction fails, future requests for input extraction will silently fail until clear()
is called.
if (std::cin.fail()) // same as (!std::cin)
{
std::cin.clear(); // Put us back in 'normal' operation mode
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Remove the bad input
}
cin
#include <iostream>
#include <limits>
void getInput()
{
int x;
std::cout << "Enter a number: ";
std::cin >> x;
if (std::cin.fail())
{
std::cin.clear(); // Put us back in 'normal' operation mode
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // And remove the bad input
std::cerr << "Error: Invalid input\n";
}
else
{
std::cout << "You entered: " << x << '\n';
}
}
Static assertions are checked at compile time and cause a compile-time error if the condition is false.
static_assert(sizeof(long) == 8, "long must be 8 bytes");
static_assert(sizeof(int) >= 4, "int must be at least 4 bytes");
A buffer is a piece of memory set aside for storing data temporarily while it is moved from one place to another.