Kurs C++ odc. 6: Instrukcja switch case. Menu główne. Błędy wejścia — Transcript
Full transcript
- 0:06Hello there. Mirosław Zelent here. In
- 0:09the sixth episode of the C ++
- 0:10programming course, we will learn a new
- 0:13instruction called switch and find out
- 0:15how to protect a program from crashing.
- 0:17In case someone enters, for example, a
- 0:19letter or another alphanumeric
- 0:20character instead of a number from the
- 0:22keyboard. We will create an application
- 0:25with a main menu, and we will also make
- 0:27it react to a keystroke without the
- 0:29need to confirm the choice with the
- 0:30Enter key. But enough with the
- 0:32introductions. Let's get to programming
- 0:34. We will start by learning the
- 0:36instruction called switch. In English,
- 0:38the word switch means a toggle or a
- 0:40redirector. Hence, this instruction is
- 0:42often referred to precisely as a switch
- 0:44. Another name is the selection
- 0:46statement. Do not confuse it with a
- 0:48conditional statement, i.e., if,
- 0:50because sometimes in a computer program
- 0:52, there is a need for the program to
- 0:54choose between several or a dozen
- 0:56possible scenarios. Such a situation
- 0:58occurs, for example, in a main menu in
- 1:00the console. After providing two
- 1:02numbers, we have as many as four
- 1:03possible options in such a calculator
- 1:05menu. We type from the keyboard which
- 1:07mathematical operation we want. After
- 1:09entering the option number, we confirm
- 1:10with enter, and the program performs
- 1:12the appropriate calculations, showing
- 1:14the result on the screen. Basically,
- 1:16without wasting time, let's go straight
- 1:18to the compiler. Since we are to write
- 1:20such a calculator, let's create
- 1:22variables to store two numbers. Let
- 1:24them be decimal numbers, right? Then
- 1:26the calculator will calculate more
- 1:27accurately than for integers. Let these
- 1:30be float type variables named x and y.
- 1:34Let's ask for these two numbers and
- 1:36read them from the keyboard. Okay, now
- 1:42let's print the available menu options
- 1:44on the screen. To save time, I prepared
- 1:47this beforehand and have it saved in
- 1:49the clipboard. I will paste them into
- 1:50the code right now. And now it remains
- 1:53for the user to choose one of the
- 1:54available options. Therefore, we will
- 1:57ask using cout. Choose. I am not typing
- 2:02endline here so that the cursor blinks
- 2:04on the same line after displaying this
- 2:06question. That seems more elegant. And
- 2:09we also need to create a variable that
- 2:11will store the number of the selected
- 2:13option entered from the keyboard. Let
- 2:15it be an int choice, of course without
- 2:17Polish characters. After the prompt, I
- 2:21type cin choice. Let's check if
- 2:25everything is okay by pressing F9. We
- 2:29see a pretty nice main menu, but for
- 2:30now, we don't have the mechanics that
- 2:32would handle it. We have as many as
- 2:34four options in the menu and the user's
- 2:36decision saved in the choice variable.
- 2:39Of course, we know the if instruction,
- 2:41but it essentially allows for a choice
- 2:43between exactly two paths for true and
- 2:45for false. However, we can, of course,
- 2:48use the if notation to handle such a
- 2:50menu. Because, we will check if someone
- 2:53didn't type a one, meaning if the
- 2:54variable choice is equal to 1. If not,
- 2:57then with else if, we will check if
- 2:59they typed a two. If not, then we will
- 3:02check if they typed three. If not, then
- 3:04we will check if they typed four. And
- 3:06if they entered something else, we’ll
- 3:08say that this option is not in the menu
- 3:10. As you can see, it’s a bit
- 3:12time-consuming, and this is where the
- 3:14switch statement comes in handy. It
- 3:16allows you to switch between a larger
- 3:18number of available options in a
- 3:20simpler way. And here is how we write
- 3:22the same logic more simply using a
- 3:23switch statement. We say: switch based
- 3:26on the value of the 'choice' variable.
- 3:31In the 'case' of—which means case in
- 3:33English—if it were a one. In the case
- 3:38that it were a two, three, four, and
- 3:40for any other value not listed before,
- 3:43'default', that is, by default, write
- 3:45that this option is not in the menu.
- 3:49Writing it with a switch statement is
- 3:51simply clearer for the programmer,
- 3:53which is why we use it. We realize we
- 3:56could write the same thing with 'if's,
- 3:58but this looks more elegant and
- 4:00organized. So now, in our code: switch
- 4:04based on the value of the' choice '
- 4:07variable. In the case that the' choice
- 4:12'variable has a value of 1, cout: "the
- 4:16result of addition is the sum x + y".
- 4:24And now the word' break '—this is the
- 4:26command that causes you to exit the
- 4:28switch after a scenario is finished. If
- 4:31that' break 'weren't there, the program
- 4:33would execute all the scenarios from
- 4:35that point on, one after another, until
- 4:37it hit a' break 'or ran out of
- 4:39scenarios. So let's not forget that
- 4:41keyword, so the program exits the
- 4:43switch statement after executing the
- 4:45requested instructions. It’s similar
- 4:47with curly braces as it is with an' if
- 4:49'. You don't need braces if there is
- 4:51only one instruction between' case 'and
- 4:53' break '. If there are two or more
- 4:55instructions, we enclose them in braces
- 4:57. Okay. So now, what should happen for
- 5:01the value 2? It is subtraction. Done.
- 5:07Now the third menu option.
- 5:09Multiplication, meaning calculating the
- 5:11product. Option number 4, division. So
- 5:17we calculate the quotient. And the last
- 5:24' default 'option, which executes by
- 5:26default if the value of the' choice '
- 5:28variable doesn't match any case
- 5:30presented above in the switch. We will
- 5:33then write that this option is not in
- 5:34the menu. Admittedly, the program will
- 5:37still crash if someone enters text
- 5:39instead of a number. We will handle
- 5:41that protection in a moment, but for
- 5:43any number not listed, the program will
- 5:45react this way. Let's test all five
- 5:48cases. addition, subtraction,
- 5:58multiplication, division, and choosing
- 6:05a wrong option, but still a digit. For
- 6:12division, of course, we should check if
- 6:14someone is trying to divide by zero. So
- 6:17if the denominator, y, is equal to 0,
- 6:23then instead of calculating, write: we
- 6:25do not divide by 0. And in the other
- 6:30case,' else ', calculate the quotient
- 6:32normally and show it on the screen.
- 6:39Okay, basically done. We can see that
- 6:41the version with the switch is much
- 6:43more readable. Here I will show you the
- 6:45same program written using ifs. Less
- 6:48clear, right? The idea of a switch is
- 6:51easy to grasp, since we already know
- 6:53ifs, right? That is why it went so
- 6:55smoothly for us. Now, two more
- 6:56improvements. First, the program ends
- 6:59after calculation and you have to
- 7:01restart it from the exe file. Not very
- 7:03convenient, in my opinion. Let's make a
- 7:06menu that loops. The math result will
- 7:09stay on screen until you press enter,
- 7:11then the main menu reappears so you can
- 7:14use the calculator again. Looking at
- 7:17this analytically, the program should
- 7:19only close when the user decides, and
- 7:21it would be best to add such an exit
- 7:23option to the main menu. Let it be
- 7:26option number 5. End of the program.
- 7:30There is an instruction that shuts down
- 7:32the entire program definitively. It is
- 7:34called exit, and in the parentheses, we
- 7:36put an int. Let it be the value zero.
- 7:39Just like after return, we always have
- 7:41zero as a symbol of finishing work. And
- 7:43the whole menu can now be wrapped in a
- 7:45loop that is infinite. For example, a
- 7:47for loop like this, which, as you can
- 7:52see, is empty inside, will run
- 7:54indefinitely. Or I could just as well
- 8:01write while true. That is also the
- 8:04simplest infinite loop. The loop can be
- 8:06infinite because exit will terminate
- 8:08the program anyway. Of course, I could
- 8:12have just as easily written while,
- 8:14meaning repeat as long as it's true
- 8:16that the choice is not five. That would
- 8:21also run until option 5 is selected,
- 8:23but I wanted to show you the exit
- 8:24instruction. Hence, I decided on an
- 8:27infinite loop. Of course, we must pause
- 8:29the program after showing the results
- 8:31on screen. First, the getchar we know
- 8:33to wait for enter. And once someone
- 8:37sees the results, we will clear the
- 8:39screen and print the menu again
- 8:42automatically in the next iteration of
- 8:44the loop. For exit to work, we need
- 8:48stdio.h at the top, and for CLS, let's
- 8:51include the cstdlib library, for
- 8:54example. It could just as well be the
- 8:57Windows library. Let's look at such a
- 9:00looped menu. As we can see, after
- 9:03pressing enter, we have the menu on the
- 9:06screen again. Only selecting option 5
- 9:08ends the whole program. Pretty cool. I
- 9:10think this makes life easier for the
- 9:12user who doesn't have to keep
- 9:13restarting the program. Another small
- 9:15improvement we can make is in how we
- 9:17select options in the menu. Right now,
- 9:19we type the number of the option we
- 9:21want and have to confirm our choice
- 9:23with enter. It would be cool to program
- 9:26it so that as soon as you press the key
- 9:28for one, the program immediately
- 9:30executes that first scenario without
- 9:32waiting for enter. And similarly for
- 9:34the other options. In a word, it will
- 9:36be a menu that reacts to pressed keys,
- 9:39responsive control like in a computer
- 9:41game. At the top, we add the conio
- 9:43library. We will change the type of the
- 9:51choice variable from int. Which simply
- 9:55means it will be a character from the
- 9:56keyboard. Instead of cin, we will write
- 10:01choice equals getch. This is also a
- 10:04function, which we read as "get
- 10:06character," meaning retrieve a
- 10:07character. However, this function from
- 10:09the conio library does not wait for the
- 10:11Enter key to be pressed. Since our
- 10:13choice is no longer an int, but a
- 10:15character from the keyboard, we need to
- 10:17write the possible values in
- 10:18apostrophes. In C ++, in apostrophes,
- 10:22which are like single quotes, we write
- 10:25single characters, that is, chars. The
- 10:28char type. One more small digression.
- 10:31The variable controlling a switch can
- 10:33be a char or an int, but not a float or
- 10:35a string. Let's remember that. An
- 10:38integral value is required, and a
- 10:40keyboard character or an int are such
- 10:42numbers. Keyboard characters are too.
- 10:44Every letter or character from the
- 10:46keyboard corresponds to a special
- 10:48number from the so-called ASCII table.
- 10:50We will talk more about this soon in
- 10:52the episode about strings. We cannot
- 10:54use string and float variables inside a
- 10:56switch statement. Let's see how it
- 10:58works. F9. I am typing numbers. And now
- 11:03I press one on the keyboard. As we can
- 11:05see, option number 1 executes
- 11:07immediately. Interestingly, since the
- 11:09choice is now a char and not an int,
- 11:11the program won't crash if I enter
- 11:13something that isn't a number. The
- 11:16crashing was related to me trying to
- 11:18save something that wasn't a number
- 11:19into an int. Now the choice is a char
- 11:22and the default option in the switch
- 11:23works, because it's a different
- 11:25character than those on the list, and a
- 11:27keyboard character doesn't have to be a
- 11:28valid number at all. It is enough that
- 11:30it is assigned a number itself. Of
- 11:33course, sometimes we will need to
- 11:35secure the program for entering
- 11:36integers, but I will talk about that in
- 11:38a moment in the next program. Although
- 11:41calculators usually have a completely
- 11:43different interface, I wanted to use
- 11:45the calculator example to show how to
- 11:47build a main menu in a console program.
- 11:49The switch statement can be useful not
- 11:51only when creating a menu. In the
- 11:53second program, we will use it for
- 11:55calculations. It will be a program that
- 11:57, after receiving a month number from
- 11:59the keyboard, displays information on
- 12:00the screen about how many days that
- 12:02month has in the calendar. Such a
- 12:04situation. When we look at the problem
- 12:06analytically, it turns out that a month
- 12:09can have 31 days. 30, and in the case
- 12:12of February, 29 or 28. The following
- 12:16months have 31 days: January, March,
- 12:19May, July, August, October, and
- 12:22December. As you can see, you can
- 12:24easily check this on the knuckles of
- 12:26your clenched fists. Therefore, all
- 12:29other months besides February have 30
- 12:32days, and February, as we said, has 28
- 12:34days or 29 if it is a leap year. 12
- 12:38months means 12 possible scenarios.
- 12:41However, after analysis, we come to the
- 12:43conclusion that we actually have three
- 12:45possible paths the program can take. So
- 12:47let's try to respond to the user
- 12:49accordingly, depending on the month
- 12:51number they provide. Let's create an
- 12:54int variable called month number. And
- 12:58ask cin for this number, then we'll
- 13:04read the input from the keyboard. And
- 13:08now it's time for our switch. Switch
- 13:11based on the month number variable. In
- 13:15the case that the value is 1 or 3, 5, 7
- 13:23, 8, 10, or 12, then reply. This month
- 13:36has 31 days. I can write it comfortably
- 13:38one after another, because by not using
- 13:40breaks, the program will execute one
- 13:42scenario after another until it
- 13:44encounters the first break. Now we see
- 13:47that the lack of a break instruction
- 13:49can prove very useful. We will proceed
- 13:51analogously for months that have 30
- 13:53days. 4, 6, 9, 11 appropriate comment,
- 14:03and finally a break. And for dessert,
- 14:06we have February, which is month number
- 14:082. We could, of course, print on the
- 14:12screen that this month has 28 or 29
- 14:14days, but to answer accurately, we
- 14:16should additionally ask what year it is
- 14:18in this scenario, because only in a
- 14:21leap year does February have 29 days,
- 14:23right? So let's create a new int
- 14:26variable. Let's ask with cout. Enter
- 14:32the year. And we will read it into this
- 14:38variable. So now we would have to make
- 14:40an if that checks whether the year is a
- 14:42leap year or not. It would seem that
- 14:45this is a trivial problem. Every leap
- 14:47year is divisible by 4 and that's it,
- 14:49but it turns out that's not true at all
- 14:51. For example, the year 1000 is
- 14:53divisible by 4, but it is not a leap
- 14:55year. Actually, the full condition
- 14:58checking if a year is a leap year looks
- 15:00like this. Well, a year is a leap year
- 15:03if it is divisible by 4. Remember that
- 15:06the percent operator is modulo, or the
- 15:08remainder of division, and at the same
- 15:10time it is not divisible by 100 or is
- 15:13divisible by 400. Then it is always a
- 15:15leap year. That is the full
- 15:17mathematical formula. Google "leap year
- 15:20" and check the results on Wikipedia.
- 15:22From there, you will be able to copy
- 15:24the condition you see on the screen.
- 15:29Okay, so if this is true, it means we
- 15:31have a leap year, so cout "this month
- 15:34has 29 days." Else, otherwise "this
- 15:45month has 28 days." Finally, a default
- 15:50for an incorrect number. Let's test how
- 15:58the program works. Great. We surely see
- 16:11and appreciate the elegance of this
- 16:13switch notation. The same program
- 16:15written with ifs would look like this,
- 16:17right? Significantly less readable?
- 16:20That is precisely why it is worth using
- 16:22a switch in your source code. We will
- 16:24be grateful to ourselves when we have
- 16:26to return to our code after some time.
- 16:29I don't know if you realize it, but
- 16:31returning to your own source code from,
- 16:33say, half a year ago, gives you the
- 16:35impression that someone else is its
- 16:36author. Hence, ensuring its readability
- 16:39is extremely important. Finally,
- 16:41another interesting fact. In this
- 16:43episode, we will introduce input data
- 16:45control, or as it is nicely called,
- 16:47validation, into the program. Notice
- 16:49that if the program receives a string
- 16:51that isn't a number instead of the
- 16:53promised integer, for example something
- 16:55like this, it will simply crash. You
- 16:58can make the program check if what it
- 17:00received from the user is actually a
- 17:02number. And if not, at least the
- 17:04program won't crash, but will report an
- 17:07error instead. Alternatively, if we can
- 17:09create a properly looped program, it
- 17:11can allow us to try entering a valid
- 17:14value again. First, let's make a
- 17:16program that, instead of crashing, at
- 17:18least tells the user it received bad
- 17:21input data. We will rebuild, as you
- 17:23might guess, the line with cin. We'll
- 17:26add an if statement that checks if cin
- 17:28happened to return false. So, if it is
- 17:31true that the expression in the
- 17:33parentheses has a value of false—
- 17:35because we have an exclamation mark,
- 17:37which is a negation—if that happens,
- 17:39we know this variable is not a number.
- 17:42We will then write an error message,
- 17:44but we will send this message to a
- 17:45special error output stream. This
- 17:48stream is called cerr, for console
- 17:50errors, error messages displayed in the
- 17:53console. And if the month number was
- 17:56not a number, we will end the program
- 17:58using the exit instruction we know.
- 18:00zero. Alternatively, some other action
- 18:03could be taken, but we'll decide just
- 18:05to end the program. For exit to work,
- 18:08we add the library cstdlib. What's nice
- 18:15about this validation method is that if
- 18:17the user enters a slightly broken
- 18:19number, for example 4e because their
- 18:21finger slipped on the keyboard, the
- 18:23program will truncate the e and just
- 18:25take the four. Pretty cool, right? Of
- 18:28course, someone might say that the
- 18:30number 4e is actually a valid number in
- 18:33hexadecimal, and they would be right.
- 18:36But we are assuming a decimal counting
- 18:38system for integers, and there are no
- 18:40characters from a to e there, nor any
- 18:42other letters. Additionally, if the
- 18:45value is a number but not in the range
- 18:47of 1 to 12, that situation will be
- 18:49caught by the default case in the
- 18:51switch. So it all complements and
- 18:54meshes together quite nicely.
- 18:55Additional validation options for
- 18:57things like text strings, email
- 18:59addresses, or alphanumeric sequences
- 19:01can be found in the cctype library. For
- 19:04now, I refer you to the Google search
- 19:06engine. And that's it as far as using a
- 19:08switch goes. Already knowing the if
- 19:10conditional statement made it easier
- 19:12for us to understand the switch case
- 19:14selection statement. Additionally, we
- 19:16showed the exit and break instructions.
- 19:18We also learned about easily creating
- 19:20infinite loops and validating input
- 19:22data in programs. That's quite a lot of
- 19:24knowledge for one episode. I hope I
- 19:26managed to show it in an accessible way
- 19:28and through the right choice of
- 19:30examples. Talk to you in the next
- 19:32episode of the series. Best regards.
- 19:34Yeah.
About this transcript
This page contains the full transcript of Kurs C++ odc. 6: Instrukcja switch case. Menu główne. Błędy wejścia by Pasja informatyki, generated from the public captions YouTube serves with the video. The transcript has 3,067 words across 451 segments, with the original timestamps preserved so you can click any line to jump to that moment in the embedded player.
What you can do with it
Use the transcript to take notes, quote the speaker, build a study guide, generate a summary with ChatGPT or Claude via the YouTube Summary tool, or export it as a timed subtitle file with YouTube to SRT. You can also re-open it in the transcriber to choose a caption track available on the video.
Free YouTube transcript tool
YouTube2Text is a free YouTube transcript generator — no signup, no daily limit. Paste any YouTube link and get the full transcript instantly, with timestamps, click-to-jump, caption language selection, AI prompts for ChatGPT, Claude, and Gemini, and exports to TXT, SRT, VTT, or Markdown.