3 Input of strings and numbers

 

This chapter covers

  • Input of numbers and strings
  • Using optional when we may not have a value
  • Working with random numbers
  • Further practice with lambdas and std::function

In this chapter, we will write a number-guessing game to practice taking inputs by using strings and numbers. We need to generate a random number to guess, accept input from a player, and report whether the player’s guess is correct. We will ensure the guess is actually a number, so we will learn about working with strings and numbers. We will give clues if the guess is wrong, starting with “too big” or “too small,” and then add more clues, such as how many digits are correct. The brief introduction to random numbers will give us a foundation for later chapters, and we will learn several more C++ features along the way.

3.1 Guessing a predetermined number

We will start with a constant number to guess. Guessing a number that never changes is not much of a game, but it means we can concentrate on dealing with user input. If we put the predetermined number in a function, we can change it later.

Listing 3.1 A number to guess
unsigned some_const_number()
{
   return 42;
}

Feel free to pick another number. We don’t need an entire function for this, but it might make the guessing-game code clearer than sending in a hard-coded or magic number. We will switch this out for a random number later. For now, all we need to do is take some user input and see if it matches.

3.1.1 Accepting user input the hard way

3.1.2 Accepting optional numeric input

3.1.3 Validation and feedback using std::function and lambdas

3.2 Guessing a random number

3.2.1 Setting up a random number generator

3.2.2 Using the random number generator

3.3 Guessing a prime number

3.3.1 Checking whether the number is prime

3.3.2 Checking properties with static_assert

3.3.3 Generating a random prime number