3 Input, 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, using strings and numbers. We need to generate a random number to guess, accept input from a player, and report if the player’s guess is correct or not. 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 a foundation for a later chapter, and we will learn several more C++ features on 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 on:
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 on. For now, all we now need to do is take some user input and see if it matches.