Age Verification

Age Verification

Implement a function named verify_age that prompts the user for their age and returns true if they are 18 or older, and false otherwise.

Answer

#include <iostream>

bool verify_age()
{
    std::cout << "Input your age: ";
    int age;
    std::cin >> age;

    if (age >= 18)
    {
        return true;
    }
    else
    {
        return false;
    }
}

int main() 
{
	if (verify_age())
	{
    		std::cout << "You are 18 or older.\n");
	}
	else 
	{
    		std::cout << "You are under 18.\n");
	}
}

Shortened version

#include <iostream>

bool verify_age()
{
	std::cout << "Input your age: ";
	int age;
	std::cin >> age;
	return age >= 18;
}

int main() 
{
    std::cout << (verify_age() ? "You are 18 or older.\n" : "You are under 18.\n");
}

This code returns the bool evaluation directly. It makes use of the ternary operator when printing.

Questions