YouTube2Text

Kurs C++ odc. 6: Instrukcja switch case. Menu główne. Błędy wejścia — Transcript

by Pasja informatyki · 3,067 words · 451 segments · language en · Watch on YouTube

Full transcript

  1. 0:06Hello there. Mirosław Zelent here. In
  2. 0:09the sixth episode of the C ++
  3. 0:10programming course, we will learn a new
  4. 0:13instruction called switch and find out
  5. 0:15how to protect a program from crashing.
  6. 0:17In case someone enters, for example, a
  7. 0:19letter or another alphanumeric
  8. 0:20character instead of a number from the
  9. 0:22keyboard. We will create an application
  10. 0:25with a main menu, and we will also make
  11. 0:27it react to a keystroke without the
  12. 0:29need to confirm the choice with the
  13. 0:30Enter key. But enough with the
  14. 0:32introductions. Let's get to programming
  15. 0:34. We will start by learning the
  16. 0:36instruction called switch. In English,
  17. 0:38the word switch means a toggle or a
  18. 0:40redirector. Hence, this instruction is
  19. 0:42often referred to precisely as a switch
  20. 0:44. Another name is the selection
  21. 0:46statement. Do not confuse it with a
  22. 0:48conditional statement, i.e., if,
  23. 0:50because sometimes in a computer program
  24. 0:52, there is a need for the program to
  25. 0:54choose between several or a dozen
  26. 0:56possible scenarios. Such a situation
  27. 0:58occurs, for example, in a main menu in
  28. 1:00the console. After providing two
  29. 1:02numbers, we have as many as four
  30. 1:03possible options in such a calculator
  31. 1:05menu. We type from the keyboard which
  32. 1:07mathematical operation we want. After
  33. 1:09entering the option number, we confirm
  34. 1:10with enter, and the program performs
  35. 1:12the appropriate calculations, showing
  36. 1:14the result on the screen. Basically,
  37. 1:16without wasting time, let's go straight
  38. 1:18to the compiler. Since we are to write
  39. 1:20such a calculator, let's create
  40. 1:22variables to store two numbers. Let
  41. 1:24them be decimal numbers, right? Then
  42. 1:26the calculator will calculate more
  43. 1:27accurately than for integers. Let these
  44. 1:30be float type variables named x and y.
  45. 1:34Let's ask for these two numbers and
  46. 1:36read them from the keyboard. Okay, now
  47. 1:42let's print the available menu options
  48. 1:44on the screen. To save time, I prepared
  49. 1:47this beforehand and have it saved in
  50. 1:49the clipboard. I will paste them into
  51. 1:50the code right now. And now it remains
  52. 1:53for the user to choose one of the
  53. 1:54available options. Therefore, we will
  54. 1:57ask using cout. Choose. I am not typing
  55. 2:02endline here so that the cursor blinks
  56. 2:04on the same line after displaying this
  57. 2:06question. That seems more elegant. And
  58. 2:09we also need to create a variable that
  59. 2:11will store the number of the selected
  60. 2:13option entered from the keyboard. Let
  61. 2:15it be an int choice, of course without
  62. 2:17Polish characters. After the prompt, I
  63. 2:21type cin choice. Let's check if
  64. 2:25everything is okay by pressing F9. We
  65. 2:29see a pretty nice main menu, but for
  66. 2:30now, we don't have the mechanics that
  67. 2:32would handle it. We have as many as
  68. 2:34four options in the menu and the user's
  69. 2:36decision saved in the choice variable.
  70. 2:39Of course, we know the if instruction,
  71. 2:41but it essentially allows for a choice
  72. 2:43between exactly two paths for true and
  73. 2:45for false. However, we can, of course,
  74. 2:48use the if notation to handle such a
  75. 2:50menu. Because, we will check if someone
  76. 2:53didn't type a one, meaning if the
  77. 2:54variable choice is equal to 1. If not,
  78. 2:57then with else if, we will check if
  79. 2:59they typed a two. If not, then we will
  80. 3:02check if they typed three. If not, then
  81. 3:04we will check if they typed four. And
  82. 3:06if they entered something else, we’ll
  83. 3:08say that this option is not in the menu
  84. 3:10. As you can see, it’s a bit
  85. 3:12time-consuming, and this is where the
  86. 3:14switch statement comes in handy. It
  87. 3:16allows you to switch between a larger
  88. 3:18number of available options in a
  89. 3:20simpler way. And here is how we write
  90. 3:22the same logic more simply using a
  91. 3:23switch statement. We say: switch based
  92. 3:26on the value of the 'choice' variable.
  93. 3:31In the 'case' of—which means case in
  94. 3:33English—if it were a one. In the case
  95. 3:38that it were a two, three, four, and
  96. 3:40for any other value not listed before,
  97. 3:43'default', that is, by default, write
  98. 3:45that this option is not in the menu.
  99. 3:49Writing it with a switch statement is
  100. 3:51simply clearer for the programmer,
  101. 3:53which is why we use it. We realize we
  102. 3:56could write the same thing with 'if's,
  103. 3:58but this looks more elegant and
  104. 4:00organized. So now, in our code: switch
  105. 4:04based on the value of the' choice '
  106. 4:07variable. In the case that the' choice
  107. 4:12'variable has a value of 1, cout: "the
  108. 4:16result of addition is the sum x + y".
  109. 4:24And now the word' break '—this is the
  110. 4:26command that causes you to exit the
  111. 4:28switch after a scenario is finished. If
  112. 4:31that' break 'weren't there, the program
  113. 4:33would execute all the scenarios from
  114. 4:35that point on, one after another, until
  115. 4:37it hit a' break 'or ran out of
  116. 4:39scenarios. So let's not forget that
  117. 4:41keyword, so the program exits the
  118. 4:43switch statement after executing the
  119. 4:45requested instructions. It’s similar
  120. 4:47with curly braces as it is with an' if
  121. 4:49'. You don't need braces if there is
  122. 4:51only one instruction between' case 'and
  123. 4:53' break '. If there are two or more
  124. 4:55instructions, we enclose them in braces
  125. 4:57. Okay. So now, what should happen for
  126. 5:01the value 2? It is subtraction. Done.
  127. 5:07Now the third menu option.
  128. 5:09Multiplication, meaning calculating the
  129. 5:11product. Option number 4, division. So
  130. 5:17we calculate the quotient. And the last
  131. 5:24' default 'option, which executes by
  132. 5:26default if the value of the' choice '
  133. 5:28variable doesn't match any case
  134. 5:30presented above in the switch. We will
  135. 5:33then write that this option is not in
  136. 5:34the menu. Admittedly, the program will
  137. 5:37still crash if someone enters text
  138. 5:39instead of a number. We will handle
  139. 5:41that protection in a moment, but for
  140. 5:43any number not listed, the program will
  141. 5:45react this way. Let's test all five
  142. 5:48cases. addition, subtraction,
  143. 5:58multiplication, division, and choosing
  144. 6:05a wrong option, but still a digit. For
  145. 6:12division, of course, we should check if
  146. 6:14someone is trying to divide by zero. So
  147. 6:17if the denominator, y, is equal to 0,
  148. 6:23then instead of calculating, write: we
  149. 6:25do not divide by 0. And in the other
  150. 6:30case,' else ', calculate the quotient
  151. 6:32normally and show it on the screen.
  152. 6:39Okay, basically done. We can see that
  153. 6:41the version with the switch is much
  154. 6:43more readable. Here I will show you the
  155. 6:45same program written using ifs. Less
  156. 6:48clear, right? The idea of a switch is
  157. 6:51easy to grasp, since we already know
  158. 6:53ifs, right? That is why it went so
  159. 6:55smoothly for us. Now, two more
  160. 6:56improvements. First, the program ends
  161. 6:59after calculation and you have to
  162. 7:01restart it from the exe file. Not very
  163. 7:03convenient, in my opinion. Let's make a
  164. 7:06menu that loops. The math result will
  165. 7:09stay on screen until you press enter,
  166. 7:11then the main menu reappears so you can
  167. 7:14use the calculator again. Looking at
  168. 7:17this analytically, the program should
  169. 7:19only close when the user decides, and
  170. 7:21it would be best to add such an exit
  171. 7:23option to the main menu. Let it be
  172. 7:26option number 5. End of the program.
  173. 7:30There is an instruction that shuts down
  174. 7:32the entire program definitively. It is
  175. 7:34called exit, and in the parentheses, we
  176. 7:36put an int. Let it be the value zero.
  177. 7:39Just like after return, we always have
  178. 7:41zero as a symbol of finishing work. And
  179. 7:43the whole menu can now be wrapped in a
  180. 7:45loop that is infinite. For example, a
  181. 7:47for loop like this, which, as you can
  182. 7:52see, is empty inside, will run
  183. 7:54indefinitely. Or I could just as well
  184. 8:01write while true. That is also the
  185. 8:04simplest infinite loop. The loop can be
  186. 8:06infinite because exit will terminate
  187. 8:08the program anyway. Of course, I could
  188. 8:12have just as easily written while,
  189. 8:14meaning repeat as long as it's true
  190. 8:16that the choice is not five. That would
  191. 8:21also run until option 5 is selected,
  192. 8:23but I wanted to show you the exit
  193. 8:24instruction. Hence, I decided on an
  194. 8:27infinite loop. Of course, we must pause
  195. 8:29the program after showing the results
  196. 8:31on screen. First, the getchar we know
  197. 8:33to wait for enter. And once someone
  198. 8:37sees the results, we will clear the
  199. 8:39screen and print the menu again
  200. 8:42automatically in the next iteration of
  201. 8:44the loop. For exit to work, we need
  202. 8:48stdio.h at the top, and for CLS, let's
  203. 8:51include the cstdlib library, for
  204. 8:54example. It could just as well be the
  205. 8:57Windows library. Let's look at such a
  206. 9:00looped menu. As we can see, after
  207. 9:03pressing enter, we have the menu on the
  208. 9:06screen again. Only selecting option 5
  209. 9:08ends the whole program. Pretty cool. I
  210. 9:10think this makes life easier for the
  211. 9:12user who doesn't have to keep
  212. 9:13restarting the program. Another small
  213. 9:15improvement we can make is in how we
  214. 9:17select options in the menu. Right now,
  215. 9:19we type the number of the option we
  216. 9:21want and have to confirm our choice
  217. 9:23with enter. It would be cool to program
  218. 9:26it so that as soon as you press the key
  219. 9:28for one, the program immediately
  220. 9:30executes that first scenario without
  221. 9:32waiting for enter. And similarly for
  222. 9:34the other options. In a word, it will
  223. 9:36be a menu that reacts to pressed keys,
  224. 9:39responsive control like in a computer
  225. 9:41game. At the top, we add the conio
  226. 9:43library. We will change the type of the
  227. 9:51choice variable from int. Which simply
  228. 9:55means it will be a character from the
  229. 9:56keyboard. Instead of cin, we will write
  230. 10:01choice equals getch. This is also a
  231. 10:04function, which we read as "get
  232. 10:06character," meaning retrieve a
  233. 10:07character. However, this function from
  234. 10:09the conio library does not wait for the
  235. 10:11Enter key to be pressed. Since our
  236. 10:13choice is no longer an int, but a
  237. 10:15character from the keyboard, we need to
  238. 10:17write the possible values in
  239. 10:18apostrophes. In C ++, in apostrophes,
  240. 10:22which are like single quotes, we write
  241. 10:25single characters, that is, chars. The
  242. 10:28char type. One more small digression.
  243. 10:31The variable controlling a switch can
  244. 10:33be a char or an int, but not a float or
  245. 10:35a string. Let's remember that. An
  246. 10:38integral value is required, and a
  247. 10:40keyboard character or an int are such
  248. 10:42numbers. Keyboard characters are too.
  249. 10:44Every letter or character from the
  250. 10:46keyboard corresponds to a special
  251. 10:48number from the so-called ASCII table.
  252. 10:50We will talk more about this soon in
  253. 10:52the episode about strings. We cannot
  254. 10:54use string and float variables inside a
  255. 10:56switch statement. Let's see how it
  256. 10:58works. F9. I am typing numbers. And now
  257. 11:03I press one on the keyboard. As we can
  258. 11:05see, option number 1 executes
  259. 11:07immediately. Interestingly, since the
  260. 11:09choice is now a char and not an int,
  261. 11:11the program won't crash if I enter
  262. 11:13something that isn't a number. The
  263. 11:16crashing was related to me trying to
  264. 11:18save something that wasn't a number
  265. 11:19into an int. Now the choice is a char
  266. 11:22and the default option in the switch
  267. 11:23works, because it's a different
  268. 11:25character than those on the list, and a
  269. 11:27keyboard character doesn't have to be a
  270. 11:28valid number at all. It is enough that
  271. 11:30it is assigned a number itself. Of
  272. 11:33course, sometimes we will need to
  273. 11:35secure the program for entering
  274. 11:36integers, but I will talk about that in
  275. 11:38a moment in the next program. Although
  276. 11:41calculators usually have a completely
  277. 11:43different interface, I wanted to use
  278. 11:45the calculator example to show how to
  279. 11:47build a main menu in a console program.
  280. 11:49The switch statement can be useful not
  281. 11:51only when creating a menu. In the
  282. 11:53second program, we will use it for
  283. 11:55calculations. It will be a program that
  284. 11:57, after receiving a month number from
  285. 11:59the keyboard, displays information on
  286. 12:00the screen about how many days that
  287. 12:02month has in the calendar. Such a
  288. 12:04situation. When we look at the problem
  289. 12:06analytically, it turns out that a month
  290. 12:09can have 31 days. 30, and in the case
  291. 12:12of February, 29 or 28. The following
  292. 12:16months have 31 days: January, March,
  293. 12:19May, July, August, October, and
  294. 12:22December. As you can see, you can
  295. 12:24easily check this on the knuckles of
  296. 12:26your clenched fists. Therefore, all
  297. 12:29other months besides February have 30
  298. 12:32days, and February, as we said, has 28
  299. 12:34days or 29 if it is a leap year. 12
  300. 12:38months means 12 possible scenarios.
  301. 12:41However, after analysis, we come to the
  302. 12:43conclusion that we actually have three
  303. 12:45possible paths the program can take. So
  304. 12:47let's try to respond to the user
  305. 12:49accordingly, depending on the month
  306. 12:51number they provide. Let's create an
  307. 12:54int variable called month number. And
  308. 12:58ask cin for this number, then we'll
  309. 13:04read the input from the keyboard. And
  310. 13:08now it's time for our switch. Switch
  311. 13:11based on the month number variable. In
  312. 13:15the case that the value is 1 or 3, 5, 7
  313. 13:23, 8, 10, or 12, then reply. This month
  314. 13:36has 31 days. I can write it comfortably
  315. 13:38one after another, because by not using
  316. 13:40breaks, the program will execute one
  317. 13:42scenario after another until it
  318. 13:44encounters the first break. Now we see
  319. 13:47that the lack of a break instruction
  320. 13:49can prove very useful. We will proceed
  321. 13:51analogously for months that have 30
  322. 13:53days. 4, 6, 9, 11 appropriate comment,
  323. 14:03and finally a break. And for dessert,
  324. 14:06we have February, which is month number
  325. 14:082. We could, of course, print on the
  326. 14:12screen that this month has 28 or 29
  327. 14:14days, but to answer accurately, we
  328. 14:16should additionally ask what year it is
  329. 14:18in this scenario, because only in a
  330. 14:21leap year does February have 29 days,
  331. 14:23right? So let's create a new int
  332. 14:26variable. Let's ask with cout. Enter
  333. 14:32the year. And we will read it into this
  334. 14:38variable. So now we would have to make
  335. 14:40an if that checks whether the year is a
  336. 14:42leap year or not. It would seem that
  337. 14:45this is a trivial problem. Every leap
  338. 14:47year is divisible by 4 and that's it,
  339. 14:49but it turns out that's not true at all
  340. 14:51. For example, the year 1000 is
  341. 14:53divisible by 4, but it is not a leap
  342. 14:55year. Actually, the full condition
  343. 14:58checking if a year is a leap year looks
  344. 15:00like this. Well, a year is a leap year
  345. 15:03if it is divisible by 4. Remember that
  346. 15:06the percent operator is modulo, or the
  347. 15:08remainder of division, and at the same
  348. 15:10time it is not divisible by 100 or is
  349. 15:13divisible by 400. Then it is always a
  350. 15:15leap year. That is the full
  351. 15:17mathematical formula. Google "leap year
  352. 15:20" and check the results on Wikipedia.
  353. 15:22From there, you will be able to copy
  354. 15:24the condition you see on the screen.
  355. 15:29Okay, so if this is true, it means we
  356. 15:31have a leap year, so cout "this month
  357. 15:34has 29 days." Else, otherwise "this
  358. 15:45month has 28 days." Finally, a default
  359. 15:50for an incorrect number. Let's test how
  360. 15:58the program works. Great. We surely see
  361. 16:11and appreciate the elegance of this
  362. 16:13switch notation. The same program
  363. 16:15written with ifs would look like this,
  364. 16:17right? Significantly less readable?
  365. 16:20That is precisely why it is worth using
  366. 16:22a switch in your source code. We will
  367. 16:24be grateful to ourselves when we have
  368. 16:26to return to our code after some time.
  369. 16:29I don't know if you realize it, but
  370. 16:31returning to your own source code from,
  371. 16:33say, half a year ago, gives you the
  372. 16:35impression that someone else is its
  373. 16:36author. Hence, ensuring its readability
  374. 16:39is extremely important. Finally,
  375. 16:41another interesting fact. In this
  376. 16:43episode, we will introduce input data
  377. 16:45control, or as it is nicely called,
  378. 16:47validation, into the program. Notice
  379. 16:49that if the program receives a string
  380. 16:51that isn't a number instead of the
  381. 16:53promised integer, for example something
  382. 16:55like this, it will simply crash. You
  383. 16:58can make the program check if what it
  384. 17:00received from the user is actually a
  385. 17:02number. And if not, at least the
  386. 17:04program won't crash, but will report an
  387. 17:07error instead. Alternatively, if we can
  388. 17:09create a properly looped program, it
  389. 17:11can allow us to try entering a valid
  390. 17:14value again. First, let's make a
  391. 17:16program that, instead of crashing, at
  392. 17:18least tells the user it received bad
  393. 17:21input data. We will rebuild, as you
  394. 17:23might guess, the line with cin. We'll
  395. 17:26add an if statement that checks if cin
  396. 17:28happened to return false. So, if it is
  397. 17:31true that the expression in the
  398. 17:33parentheses has a value of false—
  399. 17:35because we have an exclamation mark,
  400. 17:37which is a negation—if that happens,
  401. 17:39we know this variable is not a number.
  402. 17:42We will then write an error message,
  403. 17:44but we will send this message to a
  404. 17:45special error output stream. This
  405. 17:48stream is called cerr, for console
  406. 17:50errors, error messages displayed in the
  407. 17:53console. And if the month number was
  408. 17:56not a number, we will end the program
  409. 17:58using the exit instruction we know.
  410. 18:00zero. Alternatively, some other action
  411. 18:03could be taken, but we'll decide just
  412. 18:05to end the program. For exit to work,
  413. 18:08we add the library cstdlib. What's nice
  414. 18:15about this validation method is that if
  415. 18:17the user enters a slightly broken
  416. 18:19number, for example 4e because their
  417. 18:21finger slipped on the keyboard, the
  418. 18:23program will truncate the e and just
  419. 18:25take the four. Pretty cool, right? Of
  420. 18:28course, someone might say that the
  421. 18:30number 4e is actually a valid number in
  422. 18:33hexadecimal, and they would be right.
  423. 18:36But we are assuming a decimal counting
  424. 18:38system for integers, and there are no
  425. 18:40characters from a to e there, nor any
  426. 18:42other letters. Additionally, if the
  427. 18:45value is a number but not in the range
  428. 18:47of 1 to 12, that situation will be
  429. 18:49caught by the default case in the
  430. 18:51switch. So it all complements and
  431. 18:54meshes together quite nicely.
  432. 18:55Additional validation options for
  433. 18:57things like text strings, email
  434. 18:59addresses, or alphanumeric sequences
  435. 19:01can be found in the cctype library. For
  436. 19:04now, I refer you to the Google search
  437. 19:06engine. And that's it as far as using a
  438. 19:08switch goes. Already knowing the if
  439. 19:10conditional statement made it easier
  440. 19:12for us to understand the switch case
  441. 19:14selection statement. Additionally, we
  442. 19:16showed the exit and break instructions.
  443. 19:18We also learned about easily creating
  444. 19:20infinite loops and validating input
  445. 19:22data in programs. That's quite a lot of
  446. 19:24knowledge for one episode. I hope I
  447. 19:26managed to show it in an accessible way
  448. 19:28and through the right choice of
  449. 19:30examples. Talk to you in the next
  450. 19:32episode of the series. Best regards.
  451. 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.